【问题标题】:Segmentation Fault with looping through std String by character分段错误,按字符循环 std 字符串
【发布时间】: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::stringstd::cout 效果很好。检查您的包含和命名空间。 String 是在哪里为您定义的?
  • 您的Stringstd::string 的类型定义吗?如果没有,你的错误可能就在那里。 String 的构造函数发生了什么?
  • 对不起,这不应该是字符串,它只是 str::string。我在我的 for 循环中添加了一些 cout 进行测试,例如,如果输入了字符串:“1+1”,for 循环将运行 2 次,但在尝试设置 char ch = str[ 时在第三次运行时给我错误i].

标签: c++ string for-loop char


【解决方案1】:

问题是在空堆栈上调用s1.top() 是未定义的行为。您应该在调用s1.top() 之前检查! s1.empty()

堆栈通常是空的,因为代码:

for(int j=0; j < 10; j++){
     if(ch == j)
            s1.push(ch);
}

字符ch持有字符代码;字符 '0' 与整数 0 等具有不同的代码。对此的简单解决方法是 for (char j = '0'; j &lt;= '9'; ++j)

但是你可以替换整个循环;例如if ( std::isdigit(ch) ) s1.push(ch);

【讨论】:

    【解决方案2】:

    您正在尝试获取空堆栈的顶部。

    改变

    result = s1.top();
    return result;
    

    if ( s1.empty() )
    {
       return -1;
    }
    else
    {
       return s1.top();
    }
    

    【讨论】:

      猜你喜欢
      • 2015-09-03
      • 2012-11-14
      • 2020-07-06
      • 1970-01-01
      • 1970-01-01
      • 2021-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多