c++ - 按字符循环遍历 std 字符串的段错误

标签 c++ string for-loop char

我正在尝试编写一个程序,要求我逐个字符地循环遍历字符串并对其执行上述操作。这是我现在拥有的:

#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/

相关文章:

c++ - 为什么 gcc 和 NVCC (g++) 看到两种不同的结构大小?

c++ - 如何处理 GlutPostRedisplay?

c++ - const char* 是字符串还是指针

python - 删除字符串的第一个字符

r - 如何找到大于或等于 a 的值,然后在 R 中找到这些最大值中的最小值?

c++ - 如何将 QString 绑定(bind)到调用输出 varchar 的过程的 QSqlQuery?

c++ - 使用 gSoap 的异步、确认、点对点连接

c# - 如何仅将文本框条目的最后 4 位数字插入数据库?

c - 正确打印值 1 到 10

java - Java 如何处理在 for 循环中使用 getter 的情况?