所以我编写了一些代码,通过打开要复制的文件来复制文件,然后使用get从char复制char。代码是:
int main(int argc, char* argv[]) {
if (argc != 3) {
cout << "ERROR: Invalid number of arguments.\n";
return 1;
}
ifstream inputFile(argv[1]);
ofstream outputFile(argv[2]);
char c;
if (inputFile.is_open() && outputFile.is_open()) {
while (!(inputFile.eof())) {
c = inputFile.get();
outputFile << c;
}
}
else {
cout << "Unable to open file(s).\n";
return 1;
}
inputFile.close();
outputFile.close();
return 0;
}
它完全复制文本,除了总是读入垃圾字符。为什么要读入这个垃圾字符,我该如何防止这种情况? (注意:我知道有更好的方法来复制文件,但我必须使用get())。
答案 0 :(得分:2)
循环应该是这样的:
for (int c; (c = inputFile.get()) != EOF; )
{
if (!outputFile.put(c))
{
// fatal: write error, die
}
}