2014-12-05 90 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