我正在做一個字符串比較,但有一個問題。我有一個文件,其中編寫了12345
,然後我創建了另一個源文件並執行了輸入(輸入爲12345
)。然後我通過bool
true
false
邏輯進行比較,但問題是bool
從來沒有變成現實,我認爲比較中存在邏輯錯誤,但我沒有發現錯誤。我想我正面臨着一個邏輯錯誤比較
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <iostream>
using namespace std;
int
main()
{
char str[256];
char CNIC[5];
std::fstream file1;
for(int i = 0; i < 5; i++)
{
CNIC[i] = getche(); // editor's comment: probably std::getchar()
}
file1.open("D:\\UOL\\OoP\\Nadra database.txt", ios::in);
bool check = false;
while(!file1.eof())
{
file1.getline(str, 255);
if(str == CNIC)
{
check = true;
break;
}
if(check)
{
cout << endl << "CNIC number matched" << endl;
}
else
{
cout << endl << "CNIC number didn't match" << endl;
}
}
file1.close();
system("pause");
return 0;
}
使用std :: string(推薦)或strcmp。現在你要比較指向兩個char數組開頭的指針(它永遠不會相等) – Borgleader 2015-01-15 16:19:48
'if(str == CNIC)'不按照你認爲的那樣做。你需要'strcmp()'。 – 2015-01-15 16:21:16
也''file1.eof()'是錯誤的[見這裏](http://stackoverflow.com/q/5605125/583833) – Borgleader 2015-01-15 16:24:36