gpt4 book ai didi

c++ - 读取/写入 outfile 错误(可能是简单的修复)

转载 作者:行者123 更新时间:2023-11-30 05:19:21 24 4
gpt4 key购买 nike

所以我确定这里有很多“低效”代码,但我只是在学习。

我在这里遇到的问题是当我显示以前的高分时(以下列格式保存在“Score.txt”中:

NAME
score right wrong

所以看起来像这样:

Bob
40 2 2

保存乐谱效果很好,但是,ifstream 提取了错误的信息。它不显示以前的高分信息(分数 = 40,正确 = 2,错误 = 2),而是显示类似 -80883004 或类似的数字。

有人从下面的代码中看出是什么原因造成的吗?

void Score(int score, string name, int qRight, int qWrong)
{
infile.open("Score.txt");

string nameHS;
int scoreHS, rightHS, wrongHS;
char choice;

getline(infile, nameHS);
infile >> scoreHS;
infile >> rightHS;
infile >> wrongHS;

system("CLS");

cout << "You have completed Trivia!\n\n";
cout << setw(30) << "Your Score " << setw(30) << "High Score " << '\n';
cout << setw(30) << "--------------" << setw(30) << "--------------" << '\n';
cout << setw(25) << "| Score: " << setw(3) << score << " |"
<< setw(25) << "| Score: " << setw(3) << scoreHS << " |" << '\n';
cout << setw(25) << "| Right: " << setw(3) << qRight << " |"
<< setw(25) << "| Right: " << setw(3) << rightHS << " |" << '\n';
cout << setw(25) << "| Wrong: " << setw(3) << qWrong << " |"
<< setw(25) << "| Wrong: " << setw(3) << wrongHS << " |" << '\n';
cout << setw(30) << "--------------" << setw(30) << "--------------" << "\n\n";

if (score > scoreHS)
{
cout << "Congratulations! You beat the high score!\n\n";
cout << "Would you like to save your score?\n";
cout << "(Y/N): ";
cin >> choice;

if (choice == 'y' || choice == 'Y')
saveScore(score, name, qRight, qWrong);
else if (choice == 'n' | choice == 'N')
cout << "\nPlay again soon!\n\n";
else
cout << "Invalid option... game save incomplete! Good-Bye!\n\n";
}
outfile.close();
}

void saveScore(int score, string name, int qRight, int qWrong)
{
system("CLS");

cout << "Your HIGH SCORE has been saved!\n";
cout << "Good luck next game ....\n\n";

outfile.open("Score.txt", ofstream::out | ofstream::trunc);

outfile << name << '\n';
outfile << score << ' ' << qRight << ' ' << qWrong << '\n';

outfile.close();
}

最佳答案

我认为您的输入文件没有打开。打开 infile 后,添加以下检查,

bool bIsOpen = infile.is_open();

确保 bIsOpen 为真。如果它设置为 false,您可能需要将输入文件放在不同的目录中。如果您使用的是 Visual Studio,请检查工作目录并将文件放在那里。

关于c++ - 读取/写入 outfile 错误(可能是简单的修复),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41169185/

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