[英]How to search a file for a keyword, and then print the string it is contained in?
[英]How to search for a string in a file and print the line containing that string?
我必須在名為record.txt的文件中搜索字符串look_for,但是代碼不起作用。
每次我給文件中存在的look_for值時,都會說找不到記錄
string look_for, line;
in.open("record.txt");
cout<<"what is registration no of student ?";
cin>>look_for;
while(getline(in,line))
{
if(line.find(look_for)!= string::npos)
{
cout<<" record found "<<endl<<endl;
break;
}
else cout<<"record not found ";
}
您的代碼可以正常工作,但是您無需檢查文件是否可以實際打開。
像這樣修改您的代碼:
...
in.open("record.txt");
if (!in.is_open())
{
cout << "Could not open file" << endl;
return 1;
}
cout << "what is registration no of student ?";
...
無法打開文件的原因可能包括:
確保已打開文件,並且getline
返回的line
具有正確的值,並檢查文件是否具有UTF-8編碼。
#include <iostream>
#include <fstream>
#include <string>`
using namespace std;
int main()
{
string look_for, line;
int lineNumber = 0;
ifstream in("record.txt");
if (!in.is_open())
{
cout << "Couldn't open file" << endl;
return -1;
}
cout << "what is registration no of student ?\t";
cin >> look_for;
while (getline(in, line))
{
if (line.find(look_for) != string::npos)
{
cout << "Line:\t" << lineNumber << "\t[ " << look_for << " ] found in line [ " << line << " ]" << endl;
lineNumber = 0;
break;
}
lineNumber++;
}
if (lineNumber != 0)
cout << "[ " << look_for << " ] not found" << endl;
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.