文件中添加不正确

时间:2014-12-05 07:11:40

标签: c++

  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循环,但我并不完全确定。

1 个答案:

答案 0 :(得分:2)

您的情况应该是

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

然后if(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.