2012-07-11 46 views
0

我需要從C++的文本文件中複製一行文本,我有一個程序來查找一個單詞所在的行,所以我決定是否可以只需將每一行代碼加載到一個字符串中,我就可以逐行搜索,按字符串搜索,找到文件中的正確單詞及其位置(以字符而不是行)。幫助將不勝感激。將一行文本從文件複製到C++中的字符串中

編輯:我發現我使用定位線

#include <cstdlib> 
#include <iostream> 
#include <string> 
#include <fstream> 
#include <cstring> 
#include <conio.h> 

using namespace std; 

int main() 
{ 

    ifstream in_stream;   //declaring the file input 
    string filein, search, str, replace; //declaring strings 
    int lines = 0, characters = 0, words = 0; //declaring integers 
    char ch; 

    cout << "Enter the name of the file\n"; //Tells user to input a file name 
    cin >> filein;       //User inputs incoming file name 
    in_stream.open (filein.c_str(), ios::in | ios::binary); //Opens the file 


    //FIND WORDS 
    cout << "Enter word to search: " <<endl; 
    cin >> search; //User inputs word they want to search 

    while (!in_stream.eof()) 
    { 
     getline(in_stream, str); 
     lines++;     
     if ((str.find(search, 0)) != string::npos) 
     { 
      cout << "found at line " << lines << endl; 
     } 
    } 

    in_stream.seekg (0, ios::beg); // the seek goes here to reset the pointer.... 

    in_stream.seekg (0, ios::beg); // the seek goes here to reset the pointer..... 
    //COUNT CHARACTERS 

    while (!in_stream.eof())  
    { 
     in_stream.get(ch);  
     cout << ch; 
     characters ++;  
    } 
    //COUNT WORDS 

    in_stream.close();    


    system("PAUSE");      
    return EXIT_SUCCESS;  
} 
+0

請參閱編輯(我添加了您正在閱讀的文本,因爲它不會讓我發表評論沒有更多的詞) – user1519194 2012-07-11 23:30:19

回答

0

代碼,您只需要一個循環做到這一點。你的循環應該看起來像這樣:

while (getline(in_stream, str)) 
{ 
    lines++; 
    size_t pos = str.find(search, 0); 
    if (pos != string::npos) 
    { 
     size_t position = characters + pos; 
     cout << "found at line " << lines << " and character " << position << endl; 
    } 
    characters += str.length(); 
} 

我也建議你不要混用int和size_t類型。例如,字符應聲明爲size_t,而不是int。

+1

eof不是getline可能失敗的唯一原因。 getline()的返回值是用來測試的。使用'while(getline(in_stream,str))' – jthill 2012-07-13 03:39:21

+0

@jthill:好點。回答相應修改。 – 2012-07-13 04:35:32

相關問題