2014-12-05 206 views
1
if (infile.is_open()) 
    { 
     int count = 0; 
     while (infile) 
     { 
      string author, ratings; 
      getline(infile, author); 

      if (author != "") 
      { 
       getline(infile, ratings); 

      // TODO: Create new User object 
      User newuser(author, ratings); 

      // TODO: Add new User object to vector 
      userList.push_back(newuser); 

      count++; 
     } 
    } 
    cout << count << " users read in. Closing user file." << endl; 

我得到的這個輸出是從文本文件中讀入86個用戶。正確的輸出應該是32.我認爲這是因爲我正在使用while循環,但我不完全確定。文件不正確添加

+0

是什麼infile中的數據類型? ....如果你使用'Filestream infile',它是一些任意參考內存的十六進制數字(非常大的數字) – 2014-12-05 07:13:49

+0

嘗試以二進制模式打開你的文件。 – 0x499602D2 2014-12-05 07:14:32

+0

@AVIKDUTTA infile是一個整數列表 – BrandonTuley43 2014-12-05 07:14:46

回答

2

你的情況應該是這樣的

while (getline(author, infile) && getline(ratings, infile)) { 
    // validate input, then process it 
} 

然後如果(infile.open())變得微不足道。您發佈的代碼中缺少一個'}',這使得很難確切知道您的計數錯誤來自哪裏,或者這可能就是您在錯誤位置增加計數的原因。請確保你的例子完整,甚至可以編譯。

有一些小技巧,你可以只寫

userList.push_back(User(author, ratings)); 

編輯: 我創造了這個最小的測試代碼(你),並測試了以下文件,導致下面的輸出。你可否確認?請注意:目前的程式並不接受檔案中的換行符,例如然而,對於各種用戶的分組,一旦基本程序工作,這是一個很容易添加的功能。

代碼:

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

using namespace std; 

struct User { 
    string author, ratings; 
    User(string auth, string rat) 
     : author(auth), ratings(rat) {} 
}; 

int main() 
{ 
    ifstream ist("test.txt"); 
    if (!ist) { 
     cout << "Could not open file test.txt\n"; 
     return 1; 
    } 

    vector<User> userList; 
    string author, ratings; 
    size_t count = 0; 
    while (getline(ist, author) && getline(ist, ratings)) { 
     if (author != "" && ratings != "") { 
      userList.push_back(User(author, ratings)); 
      ++count; // in this case, count++ is equivalent 
     } 
    } 
    cout << count << " users read in. Closing user file.\n"; 
} 

的文件test.txt

foo 
bar 
foobar 
lalilu 
myTotalUsersAre 
3 

輸出:

3 users read in. Closing user file. 
+0

,這是我的輸出。只要相信我錯過了貼在抱歉! – BrandonTuley43 2014-12-05 07:31:22