Help in storing data into a file.

I made a quiz program. Now I wanted to keep score of the previous user.

I made a string asking the name is the user.
Then continued with the quiz.
Then added a point to output the data from the program to the file.

My code is :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//includes
//some variables and strings not related to the problem:
float score = 0;
string Name;			//User Name for File input;
string prev_score;		//Previous User's Score;
ofstream user_score ("Score.txt");
ifstream prev_user("Score.txt");

//Structs, Functions and the main function, that contains calls to these functions.

//Deriving data from file:
while( prev_user.good() )   
{
	getline (prev_user, prev_score);
	cout << prev_score << endl;
}
prev_user.close();

//Inputting Data to file:
user_score << "The previous player was: " << Name << endl;
user_score << Name << " scored " << score << " points.";
user_score.close();

//Termination....... 


So when I run the proggram, I don't get data from the file (tested it for ten consecutive times).

Please help!
Last edited on
You're opening the file for output and then input at the same time by two distinct streams. You can't that.
It had worked in another program (one I had dedicated for learning input and output to file)

So how should I have done it?

EDIT: I tried using fstream as file type and changing prev_user to user_score. No change
Last edited on
Do read process then do write processing if you want to overwrite the file.

Alternatively, write to a temp file while reading. When you're done remove the old file and replace it with the new one.

Or, open the file for read/write, read what you want and then append new data.
I did the third suggestion.
It opens the file for reading, then it should take in the data stored in the file and present it to the user. Then close the file then open it for changing the text. Then update the info in the file.

I looked for the file and found out that it was empty. So I imagine that the problem is in inputing the data into the file.
Your code is not doing the 3rd option as you're using two distict streams within your app that don't know about each other. You'd be required to open the file once, which changes your read/write code.
I changed that after your first post. Now the code is

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
fstream user_score ("Score.txt");
//.......................
//.......................
while( user_score.good() )   
{
	getline (user_score, prev_score);
	cout << prev_score << endl;
}
user_score.close();
cout << endl << endl;

//Inputting the data in file:
user_score << endl <<divider << "The previous player was: " << Name << endl;
user_score << Name << " scored " << score << " points." << divider << endl;
user_score.close();
Last edited on
Topic archived. No new replies allowed.