2013-02-28 189 views
-1

這裏是我的代碼:段錯誤 - 核心轉儲

#include <iostream> 
#include <string> 
#include <algorithm> 

using namespace std; 

string checkpalindrome(string sentence){ 
    sentence.erase(std::remove(sentence.begin(), sentence.end(), ' '), sentence.end()); 

    int unsigned i = 0; 
    for (i = 0; i < sentence.length(); i++){ 
     sentence[i] = tolower(sentence[i]); 
    } 

    if (sentence == string(sentence.rbegin(), sentence.rend())){ 
     cout << sentence << " is a palindrome." << endl; 
    } 
    if(sentence != string(sentence.rbegin(), sentence.rend())){ 
     cout << sentence << " isn't a palindrome." << endl; 
    } 
    return 0; 
} 

int main(){ 
    int x = 1; 
    string originalsentence; 
    while (x == 1){ 
     int input; 
     string sentence; 
     cout << "Press 1 to reverse a string, 2 to check a palindrome, and anything else to quit: "; 
     cin >> input; 

     if(input == 1){ 
      cout << "Enter a sentence to reverse: "; 
      cin.ignore(256, '\n'); 
      getline(cin,originalsentence); 
      sentence = originalsentence; 
      cout << string(sentence.rbegin(), sentence.rend()) << endl; 
     } 

     if(input == 2) { 
      cout << "Enter a sentence to check: "; 
      cin.ignore(256, '\n'); 
      getline(cin,originalsentence); 
      sentence = originalsentence; 
      checkpalindrome(sentence); 
     } 

     cout << "Hit 1 if you want to continue, anything else to quit: "; 
     cin >> x; 
    } 
} 

程序完成,並做一切它應該做的,當我做選項2,檢查是否有迴文,在最後,它總是除核心轉儲。我試過包括cin.ignore的,但他們沒有幫助。有任何想法嗎?

編輯1:所以我改變了g ++拋出的三個警告。他們分別是palindrome.cpp:19: warning: comparison between signed and unsigned integer expressions palindrome.cpp:29: warning: no return statement in function returning non-void palindrome.cpp:35: warning: unused variable âaâ

我把int i改爲無符號,在28返回0,並刪除了a。現在,當我編譯它沒有給出任何錯誤,但是當我運行它時仍然會在完成迴文檢查時崩潰,並出現此錯誤。 terminate called after throwing an instance of 'std::logic_error' what(): basic_string::_S_construct NULL not valid Abort (core dumped) 還有什麼想法?

+0

您是否試過編譯時打開了警告?我認爲大多數編譯器會注意到這個問題。 – 2013-02-28 18:11:22

+0

調試以確定分段溢出的確切位置。 – user1929959 2013-02-28 18:13:07

+0

所以我修復了錯誤,更新了我的上面的代碼,並且給了我一個新的錯誤! – stormcynk 2013-02-28 18:20:21

回答

0

從問題複製:

固定!我所需要做的只是return sentence,現在它沒有錯誤地出現