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

问题描述 投票:0回答:1

我只是一个初学者,尝试将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();
}
c++
1个回答
0
投票

此行

if(line.find(search))

似乎假设std::string::find将返回某些内容,如果找到了搜索字符串,则转换为true,否则返回false

如果您阅读了它的实际功能(例如here),则会发现它的返回值为:

找到的子字符串或npos的第一个字符的位置,如果找不到这样的子字符串。

因此,以上if的条件唯一为false的情况是子字符串的位置为0时(即实际上已找到)。您真正想要的是

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

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

最重要的是,您应该重新考虑您的逻辑。如果学生的名字是“ Roll”或“ Marks”怎么办?不太可能,但是在这种情况下,如果您要求将要查找的行要求为"Name: [name of student]"而不是仅要求在某个位置包含学生姓名,则可以防止代码失败。

© www.soinside.com 2019 - 2024. All rights reserved.