所以我确定这里有一些“低效率”的代码,但我只是在学习。读取/写入outfile错误(可能是简单的修复)
我在这里的问题是,当我显示前一个高分(这在下面的格式保存在“Score.txt”:
NAME
score right wrong
所以它看起来像这样:
Bob
40 2 2
保存得分完美无瑕,但是,ifstream正在拉错信息,而不是显示以前的高分信息(Score = 40,Right = 2,Wrong = 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();
}
当IO出错时(或在它出现之前),控制任何打开或读取函数的结果是很好的实践。你为什么混合使用getline和stream提取器? –
什么是更好的选择?请记住,我是新来的...我不完全确定什么是流提取器?你指的是getline和infile >>在一起吗? – Brice