读取/写入以外错误(可能简单的修复)

Reading/Writing to outfile error (Probably Simple Fix)

本文关键字:简单 错误 读取      更新时间:2023-10-16

所以我确定这里有"效率低下"代码的分配,但是我只是在学习。

我在这里遇到的问题是当我显示先前的高分(以以下格式保存在" 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,请检查工作目录并将文件放在此处。

解决问题!我忘了关闭打开文件的所有以前的实例。一定是在某种程度上引起错误。感谢那些帮助的人!