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!

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.

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.

> 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.

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.

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.

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.