【发布时间】:2023-03-25 05:55:01
【问题描述】:
我试图通过简单地使用 rdbuf() 将两个文件合并为一个,但是在合并时,文件的第一行丢失了。代码如下:
void mergeFiles(ifstream &file1, ifstream &file2, ofstream &file3) {
int num1;
int num2;
string firstLine_1;
string firstLine_2;
getline(file1, firstLine_1);
num1 = atoi(firstLine_1.c_str());
getline(file2, firstLine_2);
num2 = atoi(firstLine_2.c_str());
if (num1<num2) {
file3 << file1.rdbuf() << "\n" << file2.rdbuf();
} else {
file3 << file2.rdbuf() << "\n" << file1.rdbuf();
}
}
【问题讨论】:
-
而不是
atoi,您绝对应该只使用num1 << file1;,因为这样会更加健壮。 -
atoi让我的眼睛流血了。试试stoi(如果错误的异常是好的)或者strtoi(如果你喜欢检查返回值而不是捕获异常)或者,你可以继续使用atoi,如果你希望失败可能导致你的程序崩溃! -
@MarcusMüller:你把左右操作数(以及尖括号的方向)颠倒了,也许?
-
@BenVoigt:嗯,这确实肯定只是因为我累了。去睡觉了……