在c++中,在cin之后向文件(txt)添加新行



我正在尝试插入一些字符作为用户的输入,并将该输入保存到文本文件中。输入数据已正确添加到文本文件中,但问题是我无法添加新行。

例如,我的输入是:

a
s

d
f
g

当我打开文件时,数据显示如下:

asdfg

如何解决此问题?

#include <iostream>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
using namespace std; 
class StartMenu {
private:
string option;
public:
bool repeat = false;
bool load = false;
bool start = false;
char MenuOption;
void start_menu(){
cout << endl;
cout << "  Chose one Option to be excuted: " << endl;
cout << "  To quite press:          0 " << endl ;
cout << "  To load the game press:      1" << endl;
cout << "  To Start new Game press:         2" << endl;
cin >> MenuOption;
switch(MenuOption) {
case 48:
option = "quite" ;
repeat = true;
cout << "You choose " << MenuOption << " the game will " << option << endl;
break;
case 49:
option = "Load " ;
repeat = true;
load = true;
cout << "You choose " << MenuOption << " the game will " << option << endl;
break;
case 50:
option = "Start " ;
repeat = true;
start = true;
cout << "You choose " << MenuOption << " the game will " << option << endl;
break;

default:
cout << MenuOption <<" Number not found " << endl;
cout << "Please Enter a number between 0 - 2 "  << endl;
}
}
};
class Save_game {
public:
int openFile(){
ofstream MyWriteFile("test2.txt");
char write_to_info;
string info[52];
for (int i = 0; i < 50; i += 2){
cout << "write something" << endl;
cin >> write_to_info;
info[i] = write_to_info;
//Write to the file
MyWriteFile << info[i] << endl;
}

// Close the file
MyWriteFile.close();
return 0;
}
};
//Load Game Class 
class load_game {
public:
// Create a text string, which is used to output the text file
string my_last_game;
// Read from the text file
void Load_game(){

ifstream MyReadFile("test2.txt");
// Use a while loop together with the getline() function to read the file line by line
while (getline (MyReadFile, my_last_game)) {
//Output the text from the file
cout << my_last_game;
}
// Close the file
MyReadFile.close();
}
};
int main(){
StartMenu mymenu;
Save_game saved_game;
load_game Load_Last_game;

while(mymenu.repeat==false){
mymenu.start_menu();
}
if(mymenu.start==true){
saved_game.openFile();
}

if(mymenu.load==true){
Load_Last_game.Load_game();
}  
}

问题在于以下代码:

while (getline (MyReadFile, my_last_game)) {
//Output the text from the file
cout << my_last_game;
}

函数调用

getline (MyReadFile, my_last_game)

将从文件中读取一行并将其存储在名为my_last_gamestd::string中,但不会将换行符存储在字符串中。相反,换行符将被丢弃。

因此,如果您想打印换行符,您必须通过更改行来显式打印它

cout << my_last_game;

至:

cout << my_last_game << 'n';

相关内容

  • 没有找到相关文章