[英]Segmentation Fault with looping through std String by character
我正在嘗試制作一個程序,要求我逐個字符地遍歷一個字符串並對其進行處理。 這是我現在所擁有的:
#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。
問題是,每當我運行該程序時,當我嘗試將字符ch設置為等於字符串的最后一個字符時,都會出現分段錯誤(核心轉儲)錯誤。 誰能幫助我了解為什么我會收到此錯誤? 我已經嘗試了一切!
編輯:更新以更具體地說明程序在做什么!
問題是在空堆棧上調用s1.top()
是未定義的行為。 您應該檢查! s1.empty()
! 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);
您正在嘗試獲取空堆棧的頂部。
更改
result = s1.top();
return result;
至
if ( s1.empty() )
{
return -1;
}
else
{
return s1.top();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.