我有一個包含一個文本文件:爲什麼我的迴文功能會繼續返回錯誤?
1457887541
Madam
Able was I ere I saw Elba
Straw? No, too stupid a fad. I put soot on warts.
Class is cancelled today
,當我運行該程序,我得到的所有字符串返回false
和想不通這是爲什麼。
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <cctype>
using namespace std;
bool isPalindrome(string);
int main()
{
string input;
fstream nameFile;
nameFile.open("Xample.txt", ios::in);
if (nameFile)
{
cout << "Now reading from file: " << endl;
// Read an item from the file.
getline(nameFile, input);
// While the last read operation
// was successful, continue.
while (nameFile)
{
cout << input << endl;
//Palindrome function call
if(isPalindrome(input)){
cout << "It is a Palindrome :)/> " << endl;
}
else {
cout << "It is not a Palindrome :'(" << endl;
}
// Read the next string.
getline(nameFile, input);
}
//Close when completed
cout << "Done!" << endl;
nameFile.close();
}
else
{
cout << "ERROR: Cannot open file.\n";
}
return 0;
}
bool isPalindrome(string input){
int first = 0;
int last = input.length() - 1;
//begin loop to compare first position with last
while(last > first){
//loop if it is not a number or letter
while(!isalnum(input[first]) && !isalnum(input[last])){
first++;
last--;
}
if(tolower(input[first]) != tolower(input[last])){
return false;
}
last--;
first++;
}
return true;
}
當您使用調試器逐行執行程序時,您會觀察到哪些異常? –
在函數調用期間,您還沒有在if語句中添加「)」。 –
哎呀,我不知何故增加了一個,但我現在已經修好了。我不知道它是否是我正在使用的在線編譯器,但是我的代碼可以正常使用putty .. – user3247712