问题描述
我正在尝试创建一个简单的计数器,以保留我所解决的所有竞争性编程问题的数量。 问题在于,我试图将值保存到TXT,所以我继续添加它,但由于某种原因,它不起作用。有时给我随机数,或者在侧面增加一个数字而不是替换。例如,我从0开始,如果我加1,它将是01,依此类推。
#include <iostream>
#include <fstream>
using namespace std;
int score;
int change;
int main(){
ifstream input("score.txt");
input >> score;
ofstream output("score.txt");
cout << "So far you've solved " << score << " problems!\n";
cout << "Press 1 to add or 0 to substract\n";
cin >> change;
if (change == 1)
output << score++;
else
output << score--;
cout << "Your current score is: " << score << "\n";
output << score;
}
谢谢!
解决方法
此
ifstream input("score.txt");
input >> score;
ofstream output("score.txt");
应该是这个
ifstream input("score.txt");
input >> score;
input.close();
ofstream output("score.txt");
在尝试打开文件进行写入之前,请先关闭文件以进行读取。
更改此
if (change == 1)
output << score++;
else
output << score--;
对此
if (change == 1)
score++;
else
score--;
您的代码两次输出了score变量。
,更改此代码块:
if (change == 1)
output << score++;
else
output << score--;
收件人:
if (change == 1)
output << ++score;
else
output << --score;
您还需要摆脱此行output << score;
-不必要的行,这会导致更多问题。
然后您将获得所需的输出。
现在,其原因是因为任何后跟++
或--
的变量都将具有后递增和后递减。
因此,score++
或score--
会发出score
的原始值,但不会显示新值,尽管它会递增或递减,但在您的示例中不会显示(在控制台屏幕)。
同时预增和预减 ++score
和--score
会以 lvalue 的形式显示表达式的结果,并显示增量或递减。