gpt4 book ai didi

C++ getline() 读取文件行无限循环遍历文件

转载 作者:太空宇宙 更新时间:2023-11-04 11:37:06 31 4
gpt4 key购买 nike

我正在尝试读取文件的一行,打印出该行的部分内容,然后对文件的下一行重复该过程。

但它无法正常工作,当我将输出推送到 cmd 行时,很明显 while 循环永远不会退出。

我也尝试过使用 getline() 代替相同的过程,但我遇到了同样的问题,它只是无限地读取和重新读取文件。

这是我的代码:

fstream scores;
scores.open("scores.txt");
string playerName;
string playerScore;
int i = 0;

while (scores >> playerName >> playerScore && i < 8) {
int line = i * 40;
int rank = i + 1;

// testing
cout << rank << " " << playerName << " " << playerScore << "\n";

char plRank[1];
sprintf(plRank, "%i", (rank));
char plName[8];
sprintf(plName, "%s", "Name");
char plScore[8];
sprintf(plScore, "%s", "score");

DrawScreenString(GAX1 + 20, GAY1 + 120 + line, plRank, 0x505050, pBody);
DrawScreenString(GAX1 + 320, GAY1 + 120 + line, plName, 0x505050, pBody);
DrawScreenString(GAX1 + 570, GAY1 + 120 + line, plScore, 0x505050, pBody);
i++;
}
scores.close();

这是 cmd 行输出的摘录。

1 Edward 100
2 Jodi 80
3 Tom 50
4 Emma 40
1 Edward 100
2 Jodi 80
3 Tom 50
4 Emma 40
1 Edward 100
2 Jodi 80
3 Tom 50
4 Emma 40
1 Edward 100
2 Jodi 80
3 Tom 50
4 Emma 40
1 Edward 100
2 Jodi 80
3 Tom 50
4 Emma 40
1 Edward 100
2 Jodi 80
3 Tom 50
4 Emma 40
1 Edward 100
2 Jodi 80
3 Tom 50
4 Emma 40
...

这是 scores.txt 文件包含的内容

Edward 100
Jodi 80
Tom 50
Emma 40

如有任何关于它为何无限循环或修复的建议,我们将不胜感激!

最佳答案

I also tried the same process just using getline() instead, but I have the same problem, it just reads and re-reads the file infinitely.

您应该向我们展示了无效的 std::getline 代码。使用 std::getline 当然是这里的首选解决方案。您是否碰巧使用了成员函数而不是与 std::string 一起使用的独立函数? sprintf 和数组不是完成此任务的错误工具。

这是你应该做的:

  1. 使用独立的 std::getline 函数读取整行。
  2. 在循环条件中使用 std::getline 返回的 std::ifstream 本身(由于运算符重载,它会起作用)。
  3. 阅读每一行之后对其进行标记。如果玩家有两个名字,您是否考虑过您的程序会发生什么?这难道不应该至少导致一条有意义的错误消息吗?
  4. 使用 std::stringc_str 成员函数将字符串安全地传递给 DrawScreenString

例子:

std::string line;
while (std::getline(scores, line) && (i < 8))
{
std::vector<std::string> const tokens = tokenize(line);
// ...

DrawScreenString(GAX1 + 20, GAY1 + 120 + line, tokens[0].c_str(), 0x505050, pBody);
// and so on
}

剩下的有趣问题是如何编写tokenize函数:

std::vector<std::string> tokenize(std::string const &line)
{
// ?
}

也许 Boost Tokenizer可以帮你。但您也可以只使用 std::string 的成员函数,例如 findsubstr

只是给你一个想法:

std::vector<std::string> tokenize(std::string const &line)
{
std::vector<std::string> result;

std::string::size_type const pos_first_space = line.find(" ");
if (pos_first_space == std::string::npos)
{
// error, no space found
}
std::string const first_token = line.substr(0, pos_first_space);
result.push_back(first_token);

// ...

return result;
}

重点是:分开读取一行与标记一行。

关于C++ getline() 读取文件行无限循环遍历文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22720090/

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