读取/写入以外错误(可能简单的修复)
Reading/Writing to outfile error (Probably Simple Fix)
所以我确定这里有"效率低下"代码的分配,但是我只是在学习。
我在这里遇到的问题是当我显示先前的高分(以以下格式保存在" score.txt"中:
NAME
score right wrong
所以看起来像这样:
Bob
40 2 2
保存分数可以很好地工作,但是,ifstream正在提取错误的信息。它没有显示先前的高分信息(得分= 40,正确= 2,错误= 2),它显示了-8083004或类似的数字。
有人看到下面的代码会导致这是什么?
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!nn";
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) << "--------------" << "nn";
if (score > scoreHS)
{
cout << "Congratulations! You beat the high score!nn";
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!nn";
else
cout << "Invalid option... game save incomplete! Good-Bye!nn";
}
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 ....nn";
outfile.open("Score.txt", ofstream::out | ofstream::trunc);
outfile << name << 'n';
outfile << score << ' ' << qRight << ' ' << qWrong << 'n';
outfile.close();
}
我不认为您的输入文件正在打开。打开填充后,添加以下检查,
bool bIsOpen = infile.is_open();
确保双齿蛋白是正确的。如果将其设置为false,则可能需要将输入文件放在其他目录中。如果您使用的是Visual Studio,请检查工作目录并将文件放在此处。
解决问题!我忘了关闭打开文件的所有以前的实例。一定是在某种程度上引起错误。感谢那些帮助的人!
相关文章:
- (C++)分析树以计算返回错误值的简单算术表达式
- 显示错误输出的简单数组排序程序
- 无法找到简单的开关大小写枚举错误
- 处理简单 cpp 类构造函数中的错误
- C++20 个模块在 clang (Windows):在最简单的示例中键入信息错误
- 一个非常简单的win32套接字代码,但工作错误
- OpenGL C++(制作简单窗口时抛出错误)
- 我已经安装了用于c++编程的升华3,但在编写了一个简单的程序后,我遇到了以下错误
- boost::spirit--试图编译大多数简单代码的编译器错误
- Cmake无法在qt-creater/collect2上编译简单的测试程序:错误:ld
- 奇怪的 G++ 错误,带有关于左值和赋值的简单代码
- 编译简单的多文件类程序时出现未定义的引用错误
- 来自简单循环的 OpenAcc 错误:内核执行期间的非法地址
- 使用提升过程编译简单的应用程序会生成错误
- 标记简单错误之前的预期主表达式
- C++ 继承简单错误
- 文件输出中的简单错误检查
- 简单错误:在";"标记之前出现预期的主表达式
- 复数简单错误
- OpenGL无法渲染,可能是由于我找不到的一些简单错误