按单词搜索文件,然后在C++中打印特定行数



我只是一个初学者,尝试将 3 个不同的学生记录保存在一个文件中,然后使用学生姓名读取记录。我想要有关名称的信息,例如名称,卷号和标记。这是到目前为止的代码,但它显示整个文件。 这是我到目前为止的代码:

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
struct student
{
string name;
int rollno;
float marks;
};
main()
{
student s1,s2,s3;
int search;
string line;
cout<<"Enter Name: ";
getline(cin,s1.name);
cout<<"Enter Roll No: ";
cin>>s1.rollno;
cout<<"Enter Marks: ";
cin>>s1.marks;
cout<<endl;
cout<<"Enter Name: ";
getline(cin,s2.name);
getline(cin,s2.name);
cout<<"Enter Roll No: ";
cin>>s2.rollno;
cout<<"Enter Marks: ";
cin>>s2.marks;
cout<<endl;
cout<<"Enter Name: ";
getline(cin,s3.name);
getline(cin,s3.name);
cout<<"Enter Roll No: ";
cin>>s3.rollno;
cout<<"Enter Marks: ";
cin>>s3.marks;
cout<<endl;
ofstream fout;
fout.open("Record.txt");
fout<<"Name: "<<s1.name<<endl;
fout<<"Roll No: "<<s1.rollno<<endl;
fout<<"Marks: "<<s1.marks<<endl;
fout<<"Name: "<<s2.name<<endl;
fout<<"Roll No: "<<s2.rollno<<endl;
fout<<"Marks: "<<s2.marks<<endl;
fout<<"Name: "<<s3.name<<endl;
fout<<"Roll No: "<<s3.rollno<<endl;
fout<<"Marks: "<<s3.marks<<endl;
fout.close();
cout<<"Search By Name: ";
cin>>search;
ifstream fin;
fin.open("Record.txt");
while(getline(fin,line))
{
if(line.find(search))
{
cout<<line<<endl;
}
else
{
cout<<"Record Not Found!";
}
}
fin.close();
}

此行

if(line.find(search))

似乎假设std::string::find会返回一些转换为true的内容,以防找到搜索字符串并false否则。

如果你阅读它的实际作用(例如这里(,你会发现它的返回值是:

找到的子字符串

或 npos(如果未找到此类子字符串(的第一个字符的位置。

因此,上述if的条件计算结果为false的唯一情况是子字符串的位置0(即实际找到它(。如果您在行首写下学生的姓名,您可以尝试查看此操作。使用当前代码,只会跳过该行。你真正想要的是

if (line.find(search) != std::string::npos)

接下来,您错误地将search声明为int。您可能没有收到错误,因为find过载需要char。我本以为至少会有一个警告。无论如何,search应该是一个std::string.

修复后,您不希望为不包含您要查找的名称的每一行打印""Record Not Found!"。也许使用一个bool标志来告诉您是否已经找到了该行。

此外,当您找到正确的条目时,您必须调整代码以打印接下来的两行。

bool found = false;
while(getline(fin,line)) {
if(line.find(search) != std::string::npos) {
found = true;
cout << line << endl; 
// todo: read and print also the next two lines         
break; // leave the while loop
}
}
if (found == false) cout<<"Record Not Found!";

break是在找到正确的条目后停止读取文件。当可能有更多同名学生时,您可能希望将其删除。

最后,最重要的是你应该重新考虑你的逻辑。如果学生的名字是"卷"或"分数"怎么办?不太可能,但是如果您请求"Name: [name of student]"要查找的行,而不是仅要求在某处包含学生姓名,则可以防止代码在这种情况下失败。

最新更新