[英]Finding a string in a text file and displaying the entire line in c++
我希望我的程序在文本文件中查找学生姓名,然后显示该特定行。
我只是将文本文件的第一行作为 output 而不是我要查找的行。
void OTHERS::search_acc()
{
string srch;
string line;
fstream Myfile;
Myfile.open("STUDENTS", ios::in|ios::out);
cout << "\nEnter Student Name: ";
cin.ignore();
getline(cin, srch);
if(Myfile.is_open()) //The problem is in this if block
{
getline(Myfile, line);
line.find(srch, 0);
cout << "\nSearch result is as follows: \n" << line << endl;
}
else
{
cout << "\nSearch Failed... Student not found!" << endl;
system("PAUSE");
}
}
另外,是否可以返回我在文本文件中查找的字符串的位置?
您需要循环读取所有行,并在其中搜索每一行,例如
if(Myfile.is_open())
{
while(getline(Myfile, line)) // read all the lines
if (line.find(srch) != std::string::npos) // search each line
cout << "\nFound on this line: \n" << line << endl;
}
int line=0;
while(!Myfile.eof()){
getline(Myfile, line);
line.find(srch, 0);
++line;
}
//this line will tell you the line number
cout << "\nSearch result is as follows: \n" << line << endl;
你正在阅读一行阅读整个文件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.