C++ 如何在文件中搜索字符串并打印包含该字符串的行?
我必须在名为record.txt的文件中搜索字符串look_for,但代码不起作用 每次我给出一个值来查找文件中存在的值时,它都表示未找到记录C++ 如何在文件中搜索字符串并打印包含该字符串的行?,c++,string,file,search,find,C++,String,File,Search,Find,我必须在名为record.txt的文件中搜索字符串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(li
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”);
寻找;
while(getline(in,line))
{
if(line.find(look_for)!=string::npos)
{
cout您的代码工作正常,但是您没有检查文件是否可以实际打开
按如下方式修改代码:
...
in.open("record.txt");
if (!in.is_open())
{
cout << "Could not open file" << endl;
return 1;
}
cout << "what is registration no of student ?";
...
。。。
in.open(“record.txt”);
如果(!in.is_open())
{
请确保文件已打开,并且由getline
返回的行具有正确的值,同时检查文件是否具有UTF-8编码。\include
#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;
}
#包括
#包括`
使用名称空间std;
int main()
{
字符串查找,行;
int lineNumber=0;
ifstream in(“record.txt”);
如果(!in.is_open())
{
请发布一个……它应该包括一个简短的示例文件和一个查找
值。(首先要进行明显的检查:
中的在调用打开
后仍然有效,对吗?)我认为look\u for
结尾有换行符或其他一些字符-这破坏了find
我已经尝试过了,并且我确信文件已经成功打开…无法复制。Post a(已经有人问过你了)。可能问题出在你没有显示的代码中(这里经常发生).string look_for,line,line2;in.open(“record.txt”);coutlook_for;if(!in.is_open()){cout@KaleemKhattak请不要在注释中发布代码。编辑您的问题并放入整个程序(包括main、includes等)好了。请阅读并理解:。这太麻烦了。正确的值是什么意思?utf 8编码是什么?如何检查它