用c ++读/写文件

时间:2016-10-21 06:37:02

标签: c++

我试图让这个程序附加一个文本文件,使其成为每次迭代的新行。 它会每次都附加,但不会为每个新行添加新行。

后来,我试图让它读出文本文件中的每一行,虽然除了第一个单词之外它不会读取任何内容,并显示它。

到目前为止我所做的事情:

#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();
}

1 个答案:

答案 0 :(得分:1)

您需要指定要追加新行:

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

要阅读整行,您可以使用getlinehttp://www.cplusplus.com/reference/string/string/getline/)。

要读取整个文件,您需要循环,直到到达文件流的末尾。 Read file line by line这个帖子会帮助你。