C++中使用cin输入后向TXT文件添加换行的问题解决
问题:保存用户输入到文本文件时无法保留换行符
输入内容示例:
a s d f g
打开文件后显示为:
asdfg
问题原因
- 输入读取逻辑错误:使用
cin >> write_to_info会自动跳过所有空白字符(换行、空格、制表符等),用户输入的换行根本没被读取,自然无法写入文件。 - 文件加载输出错误:读取文件时用
getline逐行读取,但输出时直接拼接内容,没有添加换行符,导致所有内容连在一起显示。
修复方案
1. 修正输入读取方式
用cin.get(write_to_info)替换cin >> write_to_info,该函数会读取包括换行在内的所有字符,不会跳过空白。
2. 清理输入缓冲区
菜单选择后,cin >> MenuOption会将换行符留在输入缓冲区,导致第一个输入被跳过,需要在调用openFile()前清空缓冲区:
cin.ignore(numeric_limits<streamsize>::max(), '\n');
需额外包含<limits>头文件。
3. 修正文件加载时的输出逻辑
读取每行后输出时添加换行符,恢复原有的换行结构。
修改后的完整代码
#include <iostream> #include <cstdlib> #include <fstream> #include <string> #include <limits> // 用于清空缓冲区 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 << " 选择要执行的选项: " << endl; cout << " 退出请按: 0 " << endl ; cout << " 加载游戏请按: 1" << endl; cout << " 开始新游戏请按: 2" << endl; cin >> MenuOption; switch(MenuOption) { case '0': // 用字符常量替代ASCII码,提高可读性 option = "退出" ; repeat = true; cout << "你选择了 " << MenuOption << ",游戏将" << option << endl; break; case '1': option = "加载" ; repeat = true; load = true; cout << "你选择了 " << MenuOption << ",游戏将" << option << endl; break; case '2': option = "开始" ; repeat = true; start = true; cout << "你选择了 " << MenuOption << ",游戏将" << option << endl; break; default: cout << MenuOption << " 不存在的选项" << endl; cout << "请输入0-2之间的数字" << endl; } } }; class Save_game { public: int openFile(){ ofstream MyWriteFile("test2.txt"); char write_to_info; for (int i = 0; i < 50; i += 2){ cout << "输入内容:" << endl; cin.get(write_to_info); // 读取包括换行在内的所有字符 MyWriteFile << write_to_info; // 直接写入读取到的字符(含换行) } MyWriteFile.close(); return 0; } }; class load_game { public: string my_last_game; void Load_game(){ ifstream MyReadFile("test2.txt"); while (getline(MyReadFile, my_last_game)) { cout << my_last_game << endl; // 每行后添加换行,恢复原格式 } MyReadFile.close(); } }; int main(){ StartMenu mymenu; Save_game saved_game; load_game Load_Last_game; while(!mymenu.repeat){ mymenu.start_menu(); } if(mymenu.start==true){ cin.ignore(numeric_limits<streamsize>::max(), '\n'); // 清空缓冲区,避免干扰后续输入 saved_game.openFile(); } if(mymenu.load==true){ Load_Last_game.Load_game(); } }
内容的提问来源于stack exchange,提问作者Alaa Mousa
相关产品推荐
相关产品推荐

