C++使用getline读取文件异常:字符串输出乱码问题求助
C++文件读取程序的乱码与内容写入错误问题
现有一个C++程序,需求是读取text.txt的内容:将第一行写入input.txt,第二行存入expected_output变量。该程序处理数字内容时运行正常,但处理字符串时会出现输出乱码、内容写入错误的问题。
示例异常情况
当
text.txt内容为:lkhjgl 2实际运行结果:
input.txt被写入lkhjgl\n2(预期应写入lkhjgl)- 控制台输出:
2;hjgl 2;hjgl预期结果:
lkhjgl; 2;
原程序代码
#include <fstream> #include <iostream> #include <string> int main() { std::ifstream test_file("text.txt", std::ios::in); std::string input; std::string expected_output; std::string line; while (std::getline(test_file, line, '\n')) { input += line; std::getline(test_file, line, '\n'); expected_output += line; std::cout << input << ";" << std::endl; std::cout << expected_output << ";" << std::endl; std::ofstream input_file("input.txt"); input_file << input; input_file.close(); input.clear(); expected_output.clear(); } return 0; }
问题原因分析
- 循环逻辑错误:
while循环的getline会先读取第一行到line,进入循环后又调用一次getline读取第二行。当文件只有两行时,第二次getline会读取失败,但此时line的内容不会被清空,后续代码会复用旧值,导致输出乱码。 - 换行符处理问题:显式指定
'\n'作为getline的分隔符,无法兼容Windows平台的\r\n换行格式,残留的\r字符会干扰后续输出和文件写入。 - 无错误校验:未判断文件是否成功打开、行读取是否失败,异常情况下会执行错误的写入逻辑。
修复后的代码
#include <fstream> #include <iostream> #include <string> int main() { std::ifstream test_file("text.txt"); if (!test_file.is_open()) { std::cerr << "无法打开text.txt" << std::endl; return 1; } std::string input; std::string expected_output; // 读取第一行 if (std::getline(test_file, input)) { // 读取第二行 if (std::getline(test_file, expected_output)) { std::cout << input << ";" << std::endl; std::cout << expected_output << ";" << std::endl; std::ofstream input_file("input.txt"); if (input_file.is_open()) { input_file << input; input_file.close(); } else { std::cerr << "无法打开input.txt" << std::endl; return 1; } } else { std::cerr << "text.txt缺少第二行内容" << std::endl; return 1; } } else { std::cerr << "text.txt缺少第一行内容" << std::endl; return 1; } test_file.close(); return 0; }
修复说明
- 移除了不必要的
std::ios::in和显式换行符参数,使用getline默认行为自动处理不同平台的换行格式。 - 替换循环逻辑为直接读取两行,避免错误复用变量。
- 增加文件打开、行读取的错误判断,提升程序健壮性。
- 严格按照需求将第一行写入
input.txt,第二行存入变量,确保逻辑符合预期。
内容的提问来源于stack exchange,提问作者wesbi
相关产品推荐
相关产品推荐

