如何在文件中搜索字符串并打印包含该字符串的行?

时间:2017-06-15 09:19:37

标签: c++ string file search find

我必须在名为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 ";
    }

3 个答案:

答案 0 :(得分:0)

Your code works fine, but you don't check if the file could actually be opened.

Modify your code like this:

  ...
  in.open("record.txt");

  if (!in.is_open())
  {
    cout << "Could not open file" << endl;
    return 1;
  }

  cout << "what is registration no of student ?";
  ...

The reasons why the file could not be open may include:

  • the file does not exist
  • the file is not in the directory where the executable runs

答案 1 :(得分:0)

Make sure the file is opened and the line that is returned by getline has the correct value, also check that the file has UTF-8 encoding.

答案 2 :(得分:-1)

#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;
 }