我正在尝试编写一个程序,要求我逐个字符地循环遍历字符串并对其执行上述操作。这是我现在拥有的:
#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;
}
我在继续调用 loopThroughString 的程序主体中设置字符串 hello。
问题是,每次我运行该程序时,当它试图将 char ch 设置为等于字符串的最后一个字符时,我都会收到段错误(核心转储)错误。谁能帮助我理解为什么会出现此错误?我什么都试过了!
编辑:更新以更具体地说明程序正在做什么!
最佳答案
问题是调用s1.top()
是未定义行为在一个空的堆栈上。您应该检查 ! s1.empty()
打电话前s1.top()
.
栈通常是空的,因为代码:
for(int j=0; j < 10; j++){
if(ch == j)
s1.push(ch);
}
字符ch
持有字符代码;角色 '0'
与整数 0
有不同的代码等。一个简单的解决方法是 for (char j = '0'; j <= '9'; ++j)
.
但是您可以替换整个循环;例如 if ( std::isdigit(ch) ) s1.push(ch);
关于c++ - 按字符循环遍历 std 字符串的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22704728/