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

时间:2016-12-15 16:41:19

标签: c++ string variables int ifstream

所以我确信这里有一些“效率低下”的代码,但我只是在学习。

我在这里遇到的问题是当我显示以前的高分时(以“以下格式”保存在“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();
}

2 个答案:

答案 0 :(得分:1)

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

bool bIsOpen = infile.is_open();

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

答案 1 :(得分:0)

问题解决了!我忘了关闭打开文件的所有先前实例。一定是以某种方式导致错误。感谢那些帮助过的人!