![](/img/trans.png)
[英]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.