这是我的代码:
#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's,但他们没有帮助。有什么想法吗?
编辑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 :(得分:0)
复制自问题:
固定!我需要做的只是return sentence
,它现在没有错误