Ignacio R. de Almeida
Ignacio R. de Almeida

Reputation: 21

Assign value from a txt to a variable to keep a counter - C++

I am trying to create a simple counter that keeps the count of all the Competitive Programming Problems that I solve. The issue with it is that I am trying to save the value to a TXT so then I just keep adding to that but for some reason, it is not working. It sometimes gives me random numbers or it adds a number to the side instead of replacing. For example, I start with 0 and if I add 1 it will be 01 and so on.

#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; 

}

Thanks!

Upvotes: 2

Views: 342

Answers (2)

john
john

Reputation: 87957

This

ifstream input("score.txt");
input >> score;
ofstream output("score.txt");

should be this

ifstream input("score.txt");
input >> score;
input.close();
ofstream output("score.txt");

Close the file for reading before you try to open it for writing.

Change this

if (change == 1)
     output << score++;
else
     output << score--;  

to this

if (change == 1)
     score++;
else
     score--;  

Your code is outputing the score variable twice.

Upvotes: 3

AngryParticle
AngryParticle

Reputation: 1539

Changing this block of code:

if (change == 1)
    output << score++;
else
    output << score--;

to:

 if (change == 1)
    output << ++score;
else
    output << --score;

You also need to get rid of this line output << score; - Unnecessary line that causes more issues.

Then you will get your desired output.

Now, the reason for this is because any variable that has ++ or -- after will have a post-increment and post-decrement.

So score++ or score-- will emit the original value of score and not show the new value, although it will increment or decrement, but will not show in your example (on the console screen).

While, pre-increment and pre-decrement ++score and --score will emit the expression's result as an lvalue and show the increment or decrement.

Upvotes: 1

Related Questions