簡體   English   中英

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

[英]How to search for a string in a file and print the line containing that string?

我必須在名為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 ";
    }

您的代碼可以正常工作,但是您無需檢查文件是否可以實際打開。

像這樣修改您的代碼:

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

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

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

無法打開文件的原因可能包括:

  • 該文件不存在
  • 該文件不在可執行文件運行的目錄中

確保已打開文件,並且getline返回的line具有正確的值,並檢查文件是否具有UTF-8編碼。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM