gpt4 book ai didi

c++ - 从文件中添加不正确

转载 作者:行者123 更新时间:2023-11-30 03:58:41 28 4
gpt4 key购买 nike

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

最佳答案

你的情况应该是这样的

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.

关于c++ - 从文件中添加不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27310710/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com