[英]C++ If text file contains specific word or not
如果他/她輸入的數據(單詞)存在於.txt文件中,我需要可以驗證輸入的內容。 如果只有一種情況,我的代碼將正常工作。
if(line.find("2014-1113") != string::npos)
但是,當我嘗試添加else條件時。每次運行程序時,else條件始終是輸出。 我不知道為什么
我嘗試進行一個實驗,以便如果用戶輸入的txt文件中不存在的單詞,將顯示輸出錯誤,表明他/她輸入的數據有問題。 當我使用調試模式運行時。 這是輸出:
cout << "NOT FOUND!";
break;
在運行它之前,即使我更改了單詞並且它存在於我的txt文件中,仍然會輸出ELSE條件。
有人知道我的問題嗎? 謝謝!
這是我的示例txt文件:
2015-1111,Christian Karl,M
2015-1112,Joshua Evans,M
2015-1115,Jean Chloe,F
2015-1113,Shairene Traxe,F
2015-1114,Paul Howard,M
然后我的代碼:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream stream1("db.txt");
string line ;
while( std::getline( stream1, line ) )
{
if(line.find("2015-1113") != string::npos){ // WILL SEARCH 2015-1113 in file
cout << line << endl;
}
else{
cout << "NOT FOUND!";
break;
}
}
stream1.close();
system("pause");
return 0;
}
當代碼經過第一行時,找不到所需的內容,而是進入else子句。 然后,它打印“找不到”並中斷( break
終止while循環)。
您應該按照以下思路進行操作:
bool found = false;
while( std::getline( stream1, line ) && !found)
{
if(line.find("2015-1113") != string::npos){ // WILL SEARCH 2015-1113 in file
cout << line << endl;
found = true;
// If you really want to use "break;" Here will be a nice place to put it. Though it is not really necessary
}
}
if (!found)
cout << "NOT FOUND";
由於if條件在循環內,因此else語句將針對不包含要搜索內容的每一行運行。 您需要做的是使用bool標志並將其設置在循環中。 循環完成后,您可以檢查標志並查看是否找到該行。
bool found = false;
while(std::getline(stream1, line) && !found )
{
if(line.find("2015-1113") != string::npos){ // WILL SEARCH 2015-1113 in file
found = true;
}
}
if (found)
std::cout << "Your line was found.";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.