【发布时间】:2014-05-07 10:28:41
【问题描述】:
我正在尝试制作一个程序,该程序要求我逐个字符地循环字符串并对其执行上述操作。这是我现在拥有的:
#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。
问题是每次我运行程序时,当它尝试将 char ch 设置为字符串的最后一个字符时,我都会遇到 Segmentation fault (core dumped) 错误。谁能帮我理解为什么我会收到这个错误?我什么都试过了!
编辑:更新以更具体地说明程序正在做什么!
【问题讨论】:
-
对我来说看起来不错。您确定此代码是问题的原因吗?省略的代码是否修改
str? -
使用
std::string和std::cout效果很好。检查您的包含和命名空间。String是在哪里为您定义的? -
您的
String是std::string的类型定义吗?如果没有,你的错误可能就在那里。String的构造函数发生了什么? -
对不起,这不应该是字符串,它只是 str::string。我在我的 for 循环中添加了一些 cout 进行测试,例如,如果输入了字符串:“1+1”,for 循环将运行 2 次,但在尝试设置 char ch = str[ 时在第三次运行时给我错误i].