我试图让这段代码将一个输入文件分成两个文件。我希望代码拆分,以便一个新文件包含所有奇数字符,另一个文件包含所有偶数字符。我的代码没有给我任何错误,它生成了两个新文件,但是这两个新文件中没有任何内容。我想知道我的代码有什么问题(我确信它有很多问题)。我对编程还是很陌生。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void split(char sourceFile[], char destFile1[], char destFile2[]) {
int chars = 0;
ifstream sFile;
sFile.open(sourceFile);
ofstream file1;
file1.open(destFile1);
ofstream file2;
file2.open(destFile2);
while (!sFile.eof()) {
sFile.read(sourceFile + chars, 1);
cout << sourceFile[chars];
if (chars % 2 == 0) {
file1 << sourceFile[chars];
} else {
file2 << sourceFile[chars];
}
chars++;
}
}
int main() {
split("text.txt", "one.txt", "two.txt");
return 0;
}
最佳答案
它有很多错误(如你所说)
1) 你所有的文件都是ifstream
,如果你想输出到一个文件使用ofstream
。
2) 您不应尝试将文件名用作代码的变量。只需声明一个新的 char 变量。
3) 使用get not read 来读取单个字符。
4) 正确测试文件结尾。
5) 不要关闭循环内的文件,实际上根本不要关闭文件,它会在您退出函数时自动发生。
6) chars%2 == 5
究竟是什么?这永远不会是真的。
综合考虑
char ch;
while (sFile.get(ch))
{
if (chars % 2 == 0)
file1 << ch;
else
file2 << ch;
chars++;
}
关于c++ - 试图在 C++ 中将一个文本文件拆分为多个文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13520830/