2013-02-13 51 views
0

我想從一個文本文件中讀取和文件的格式是文件輸入和處理數據

方法1
方法2
插入3「詹姆斯譚」

我目前使用ifstream打開文本文件並讀取項目,但是當我使用>>讀取行時,導致名稱不能完全讀爲「James Tan」。 下面附上的是代碼和輸出。

ifstream fileInput; 

    if(fileInput.is_open()){ 
     while(fileInput.good()){ 
    fileInput >>methondName>>value>>Name; 
    ...... 

輸出

methodName = Method, Method, Insert 
value = 1, 2, 3 (must be a usigned integer) 
Name = James 

有什麼更好的方式來處理線條和內容的閱讀。 我被告知getline。但我明白,getline完全是作爲一行而不是單個單詞的單詞。

接下來是fstream真的很快嗎?原因,我想處理500000行數據,如果ifstream速度不快,我還有什麼其他選項。

請對此提出建議。

+1

您不應該真正執行'while(stream.good())...',而且您甚至不需要檢查文件是否打開。只要打開文件,並執行'while(stream >> input >> input2)...'。 – 2013-02-13 17:23:01

回答

3

方法1種
方法2
插入3 「詹姆斯譚」

我想你的意思是,該文件由幾行組成。每一行都以單詞「方法」或單詞「插入」開頭,每一行後面跟一個數字。此外,開始「插入」的行在結尾處具有多字詞名稱。

是嗎?如果是這樣,請嘗試:

ifstream fileInput("input.txt"); 
std::string methodName; 
int value; 
while (fileInput >> methodName >> value) { 
    std::string name; 
    if(methodName == "Insert") 
    std::getline(fileInput, name); 

    // Now do whatever you meant to do with the record. 
    records.push_back(RecordType(methodName, value, name); // for example 
}