2016-12-15 47 views
1

所以我确定这里有一些“低效率”的代码,但我只是在学习。读取/写入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(); 
} 
+0

当IO出错时(或在它出现之前),控制任何打开或读取函数的结果是很好的实践。你为什么混合使用getline和stream提取器? –

+0

什么是更好的选择?请记住,我是新来的...我不完全确定什么是流提取器?你指的是getline和infile >>在一起吗? – Brice

回答

1

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

bool bIsOpen = infile.is_open(); 

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

+0

添加了检查来验证infile正在打开,并且它仍然不确定问题是什么。 – Brice

+0

您的代码在我的电脑上运行。我正在使用Visual Studio 2015.你的开发环境是什么?也许你的输入文件有问题? – zooropa

+0

这很奇怪,我也在使用VS 2015。我似乎无法找到输入文件的任何错误。我已经手动输入,并依靠我的输出格式化,并用所使用的数据替换.....你真的复制/粘贴我的代码,它工作正常吗? – Brice

0

问题解决了!我忘了关闭所有以前的打开文件的实例。不知何故,一定会造成错误。感谢那些帮助过的人!

+0

给我一些爱和投票我的帖子。 :)我至少让你朝着正确的方向前进,那就是你的输入文件。我很高兴看到你有事情的工作。祝你好运! – zooropa

+0

我收到你了!感谢帮助的人。非常感激。 – Brice