I want to create a highscore system, how can i write to the file and save the input, and how to i output the data on the text file if the user selects the 2nd option?
Use a loop, reading scores until none are left.
You should also prefer to keep fstream objects in as small a namespace as possible.
1 2 3 4 5 6 7 8
elseif (option == 2)
{
ifstream scoresfile( scores_file_name );
cout << "You have selected '2.' Here are the current highscores\n";
int x;
while (scoresfile >> x)
cout << x << "\n";
}
Typically a high-scores file will also list the name of the player who scored so well. You can do that easily enough: put the number first and the name last. Your highscores.txt file might look something like this:
So i can write 10 numbers to a file, and when i open the file all 10 numbers are there. But when i want to read from the file, it only reads the last number. How do i change it so it reads everything from the file. Is there a way i can just read the whole file and output it?
#include <iostream>
#include <fstream>
usingnamespace std;
// So i can write 10 numbers to a file, and when i open the file
// all 10 numbers are there.
void create_file(constchar * fname)
{
ofstream fout(fname);
for (int n : { 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 })
fout << n << '\n';
}
int main()
{
constchar * filename = "data.txt";
// first create a file for testing
create_file(filename);
// Just read the whole file and output it.
ifstream fin( filename );
int m;
while ( fin >> m )
cout << m << '\t';
}