2017-06-15 66 views
0

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

請發表[mcve]。 –

+5

...應該包含一個簡短的示例文件和一個'look_for'值。 – Rook

+2

(首先明確檢查:'in'在你調用'open'後仍然有效,對吧?) – Rook

回答

0

你的代碼工作正常的文件,但你不檢查文件實際上可以打開。

修改你的代碼是這樣的:

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

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

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

文件爲什麼不能打開的原因可能包括:

  • 該文件不存在
  • 文件不在目錄可執行文件運行的地方
+0

我已經嘗試過了,我確定該文件正在成功打開.... –

+2

無法重現。發佈[mcve](你已經被問過了)。也許問題出在你沒有顯示的代碼中(它總是在這裏發生)。 –

+0

string look_for,line,line2; in.open(「record.txt」); cout <<「什麼是學生註冊號?」; cin >> look_for; if(!in.is_open()) cout <<「無法打開文件」<< endl; } 而(函數getline(輸入,線路)){ 如果 (line.find(look_for)=字符串::非營利組織!) { 的cout << 「記載見於」 << ENDL << ENDL; 休息; } else cout <<「record not found」; } –

0

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

+0

什麼意思是正確的價值和什麼是utf 8編碼如何檢查它 –

-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; 
} 
相關問題