c++ - 试图在 C++ 中将一个文本文件拆分为多个文本文件

标签 c++

我试图让这段代码将一个输入文件分成两个文件。我希望代码拆分,以便一个新文件包含所有奇数字符,另一个文件包含所有偶数字符。我的代码没有给我任何错误,它生成了两个新文件,但是这两个新文件中没有任何内容。我想知道我的代码有什么问题(我确信它有很多问题)。我对编程还是很陌生。

#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/

相关文章:

C++ std::unique_ptr 从函数返回并测试 null

c++ - 为什么该代码不绘制 Sprite C++ SFML

c++ - std::bad_cast vs NULL,有什么区别?

c++ - 如何编写用于rapidjson反序列化的嵌套处理程序?

c++ - 删除在C++中静态函数中分配的内存

c++ - 如何在ubuntu上的opencv和dlib上裁剪图像

c++ - 从 QVariantList 获取字符串

c++ - Erlang 和 C/C++ 线程

c++ - CUDA thrust::device_vector 类 |错误

c++ - 将二维数组从 c++ xll 返回到 excel,返回