2013-03-12 127 views
2

我正在使用STL。我需要讀取文本文件中的行。如何閱讀行,直到第一個\n,但直到第一個' '(空間)?如何從文件中讀取整行(帶空格)?

例如,我的文本文件包含:

Hello world 
Hey there 

如果我寫這樣的:

ifstream file("FileWithGreetings.txt"); 
string str(""); 
file >> str; 

然後str將只包含 「你好」,但我需要的 「Hello world」(直到第一個\n)。

我想我可以使用方法getline()但它要求指定要讀取的符號數。就我而言,我不知道我應該閱讀多少個符號。

+1

使用[其他的,更好的'getline'(http://en.cppreference.com/w/cpp/string/basic_string/getline)。 – jrok 2013-03-12 13:18:20

+0

@jrok謝謝,我現在正在使用'getline()'。 – Vladimir 2013-03-26 07:22:02

回答

8

您可以使用函數getline:使用

#include <string> 
#include <iostream> 

int main() { 
    std::string line; 
    if (getline(std::cin,line)) { 
     // line is the whole line 
    } 
} 
+0

謝謝!這解決了我的問題。在新評論中,我將展示我的新代碼。 – Vladimir 2013-03-12 13:35:33

2

getline功能是一個選項。

getc用do-while循環

讀取每個字符,如果文件中包含數字,這將是一個更好的方式來閱讀。

do { 
    int item=0, pos=0; 
    c = getc(in); 
    while((c >= '0') && (c <= '9')) { 
     item *=10; 
     item += int(c)-int('0'); 
     c = getc(in); 
     pos++; 
    } 
    if(pos) list.push_back(item); 
    }while(c != '\n' && !feof(in)); 

嘗試,如果你的文件包含字符串修改此方法..

+1

當庫提供合適的機制時,不需要手動讀取字符。 – 2013-03-12 14:01:32

1

我建議:

#include<fstream> 

ifstream reader([filename], [ifstream::in or std::ios_base::in); 

if(ifstream){ // confirm stream is in a good state 
    while(!reader.eof()){ 
    reader.read(std::string, size_t how_long?); 
    // Then process the std::string as described below 
    } 
} 

有關的std :: string,任何變量名就行了,如何長,無論你覺得合適還是使用std :: getline如上。

要處理線,只需要使用一個迭代器上的std :: string:

std::string::iterator begin() & std::string::iterator end() 

,直到你有\ n和「」你正在尋找通過文字處理迭代器指針字符。

0

感謝所有回答我的人。我做了新的代碼爲我的程序,它的工作原理:

#include <iostream> 
#include <fstream> 
#include <string> 

using namespace std; 

int main(int argc, char** argv) 
{ 
    ifstream ifile(argv[1]); 

    // ... 

    while (!ifile.eof()) 
    { 
     string line(""); 
     if (getline(ifile, line)) 
     { 
      // the line is a whole line 
     } 

     // ... 
    } 

    ifile.close(); 

    return 0; 
} 
+0

1.最好像'while(ifile)'一樣聲明條件,因爲'ifstream'已經重載了'operator bool() '來測試它是否好。 2.不要明確關閉'ifile'。這是根據RAII原理在'ifstream'析構函數中隱式完成的。 – Mikhail 2016-04-24 16:22:56

+0

3.不要爲'std :: string'指定「」值 - 它只是多餘的,字符串在默認構造函數中用「」初始化。 4.你有兩個測試:'while'和'if',而其中一個就足夠了,就是'getline'。將它移動到'while'狀態,你根本不需要測試'ifile'。 – Mikhail 2016-04-24 16:25:38