-2

I'm trying to have this program append a text file, making it a new line with every iteration. It will append every time, but not add new lines for each new line.

Afterwords, I am trying to have it read out every line in the text file, though it will not read anything but the first word, and display that.

That's what I've done so far:

#include<iostream>
#include<string>
#include<fstream>
#include<ios>
using namespace std;

/*
Return types: void
Types: 1 string, 1 int
Purpose: write to the highscores.txt
*/
void Write_Score(string name, int score);

/*
Return type: Void
Types: N/A
Purpose: Read the highscores.txt
*/
void Read_Score();

int main()
{
string usr_name;
int usr_score = 0;
cout << "Enter your name: ";
cin >> usr_name;
cout << endl;
cout << "Enter your score: ";
cin >> usr_score;
cout << endl;
Write_Score(usr_name, usr_score);
cout << endl << endl << endl;
Read_Score();

}

void Write_Score(string name, int score)
{
ofstream outfile;
outfile.open("Highscores.txt", ios::app);
outfile << name << "\t" << score;
outfile.close();
}

void Read_Score()
{
string name;
int score = 0;
ifstream infile;
infile.open("Highscores.txt", ios::in);
infile >> name >> score;
cout << name << "\t" << score << endl;
infile.close();
}
D33tly
  • 1
  • 1

1 Answers1

1

You need to specify that you want a new line to be appended:

void Write_Score(string name, int score)
{
ofstream outfile;
outfile.open("Highscores.txt", ios::app);
outfile << name << "\t" << score << std::endl;
outfile.close();
}

To read a whole line you can use getline (http://www.cplusplus.com/reference/string/string/getline/).

And to read the whole file you need to loop until you reach the end of the filestream. Read file line by line this thread will help you with that.

Community
  • 1
  • 1
Henningsson
  • 1,275
  • 1
  • 16
  • 23