2013-12-08 58 views
0

我的文本文件包含如果語句不工作,甚至說法是正確的

Wew213 
Wew214 
Wew215 

和我的程序輸入是

Wew213 

,但它告訴我輸出

"Not Matched" 

其實什麼我正在做的是我想輸入輸入,如果輸入匹配文本文件中的數字,它應該運行if語句的輸出否則els Ë聲明

這裏是我的程序

char file_data[10]; 
std::ifstream file_read ("D:\\myfile.txt"); 
cout<<"Enter the number to search"<<endl; 
char val[10]; 
cin>>val; 
while(!file_read.eof()) 
{ 
    file_read>>file_data; 
    cout<<file_data<<endl; 
    } 
    if (val == file_data) 
    { 
     cout<<"Matched"<<endl; 
    } 
    else 
    { 
      cout<<"Not Matched"<<endl; 
    } 
} 
+4

'while(!eof(file))'[always always](http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong)。 – 2013-12-08 21:12:28

+0

@ H2CO3我讀了兩遍,但沒有明白他的意思,這是'while(!eof(file))'再次讀取文件比它需要 – AHF

+0

Yap。 [15個字符] – 2013-12-08 21:45:05

回答

8

你是比較指針值,這是不同的

你需要使用strcmp比較C字符串。或使用std::string

if (strcmp(val, file_data) == 0) 
{ 
    cout<<"Matched"<<endl; 
} 
else 
{ 
     cout<<"Not Matched"<<endl; 
} 

if (std::string(val) == std::string(file_data)) 
{ 
    cout<<"Matched"<<endl; 
} 
else 
{ 
     cout<<"Not Matched"<<endl; 
} 
4

==測試地址valfile_data進行比較。而不是==,要比較字符數組的內容使用功能strcmp()

1

字符數組沒有比較運算符。因此,不是比較數組,而是比較數組第一個元素的地址。

4

給定的代碼,

char file_data[10]; 
std::ifstream file_read ("D:\\myfile.txt"); 
cout<<"Enter the number to search"<<endl; 
char val[10]; 
cin>>val; 
while(!file_read.eof()) 
{ 
    file_read>>file_data; 
    cout<<file_data<<endl; 
    } 
    if (val == file_data) 
    { 
     cout<<"Matched"<<endl; 
    } 
    else 
    { 
      cout<<"Not Matched"<<endl; 
    } 
} 

看起來像這樣通過的astyle它運行後:

char file_data[10]; 
    std::ifstream file_read ("D:\\myfile.txt"); 
    cout<<"Enter the number to search"<<endl; 
    char val[10]; 
    cin>>val; 
    while(!file_read.eof()) 
    { 
     file_read>>file_data; 
     cout<<file_data<<endl; 
    } 
    if (val == file_data) 
    { 
     cout<<"Matched"<<endl; 
    } 
    else 
    { 
     cout<<"Not Matched"<<endl; 
    } 
} 

因此,由於檢查是循環後進行,只檢查最後通過循環讀取的項目,即使你有字符串比較本身正確,你的程序將無法正常工作。

比較不起作用,因爲像其他人一樣(涌入)已經注意到,您正在比較指針而不是字符串。

要比較字符串,請使用std::string而不是字符數組。


小幅調整:不是

while(!file_read.eof()) 

while(!file_read.fail()) 

或只是

while(file_read) 

這就要求fail你(否定結果)。

但是這樣做你會必須檢查輸入操作的成功/失敗。

而且常見的成語是直接做:

while(file_read>>file_data) 
2

==運算符將只比較地址。您將需要使用strcmp函數。