2014-03-28 77 views
0

我想要制作一个程序,要求我通过字符来循环访问字符串,并对其进行说明。这里是我现在有:通过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等于字符串的最后一个字符时。任何人都可以帮助我理解为什么我得到这个错误?我已经尝试了一切!

编辑:更新为更具体关于该程序正在做什么!

+0

这看起来好像没什么问题。你确定这段代码是问题的原因吗?省略的代码是否修改'str'? – wallyk

+3

使用'std :: string'和'std :: cout'工作得很好。检查你的包含和命名空间。为你定义的“String”在哪里? – Jens

+0

你的'String'是'std :: string'的typedef吗?如果没有,你的错误可能在那里。 String的构造函数中发生了什么? –

回答

2

问题是在空堆栈上调用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 <= '9'; ++j)

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

1

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

变化

result = s1.top(); 
return result; 

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