0
void highscore1()
{
	ifstream readfile;
	int score;

	readfile.open("highscore1.txt");

	while(readfile >> score)
	{
		score += 1;
		ofstream writescore;
		writescore.open("highscore1.txt");
		writescore << score;
		writescore.close();
	}

	readfile.close();

	cout << endl;
	game();
}

how to i read from the text file, highscore1.txt and do a +1 to the integer inside the textfile and finally write the score into highscore1.txt?

Problem: my highscore1.txt show as -858993454. If i change it to zero or any other number, it will sucessfully +1 to it. so how do i if(score == ""), write 0 to it? i tried but show char * cannot change to int or something similar problem like this.

thanks!

3
Contributors
7
Replies
8
Views
8 Years
Discussion Span
Last Post by adelphe
0

You're reading AND writing the same file at the same time.

Read from the old one, write to the new one.
When you're done, delete the old and rename the new.

0

what if the file i am writing and reading to does not exist? this is what i am try solve or asking for help.

sorry if my question is not understanding, my english is poor.

0

> what if the file i am writing and reading to does not exist?
Test the result of the first attempt to open the file (you're assuming success at the moment).

If it doesn't exist, just write a new highscore table.

0

I tried doing it but doesnt understand much.

if(score == "") // in this case i assume score is nothing since the file doesnt exit so it will have no value.

but doesnt seem to be working.

0

what if the file i am writing and reading to does not exist? this is what i am try solve or asking for help.

ifstream is for reading from a file (input)
ofstream is for writing to a file (output)
fstream is for reading & writing from a file, however it will not create a file that doesn't exist, whereas ofstream will.

Therefore, what I try to do is to open a file first. If it fails then I create the file and then try to open it again.

fstream file;

//Try to open file for both read/write
file.open("data.txt");

//If the file doesn't exist it will fail
if (file.fail())
{
            cout << "Creating data file...\n";
            ofstream out;
            out.open("data.txt"); //create the file
            out.close(); //we want read/write so close it
            file.open("data.txt");  //open with read/write
}

So to answer your question of how to open a file that doesn't exist.... just create it with ofsteam.

0

thanks for the help necrolin. now i understand more on iostream !

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.