我想要制作一个程序,要求我通过字符来循环访问字符串,并对其进行说明。这里是我现在有:通过std循环的分段错误字符串按字符
#include <iostream>
#include <stack>
#include <string>
int loopThroughString(const string& hello);
int main(void){
while (true) {
cout << "String? " ;
string s;
cin.ignore();
getline(cin, s);
if (s.length() == 0){
break;
}
int answer = loopThroughString(s);
cout << answer << endl;
}
cout << endl;
}
int loopThroughString(const string& hello){
int answer;
string str = hello;
char ch;
stack<int> s1;
for(unsigned int i = 0; i <str.size(); i++){
ch = str[i];
cout << "character ch of hello is: " << ch << "\n";
for(int j=0; j < 10; j++){
if(ch == j)
s1.push(ch);
}
}
result = s1.top();
return result;
}
我设置字符串hello在继续调用loopThroughString的程序的主要。
问题是,当我每次运行程序时,都会遇到Segmentation fault(核心转储)错误,当它试图设置char ch等于字符串的最后一个字符时。任何人都可以帮助我理解为什么我得到这个错误?我已经尝试了一切!
编辑:更新为更具体关于该程序正在做什么!
这看起来好像没什么问题。你确定这段代码是问题的原因吗?省略的代码是否修改'str'? – wallyk
使用'std :: string'和'std :: cout'工作得很好。检查你的包含和命名空间。为你定义的“String”在哪里? – Jens
你的'String'是'std :: string'的typedef吗?如果没有,你的错误可能在那里。 String的构造函数中发生了什么? –