微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

逐字复制文件

如何解决逐字复制文件

我有这个功能可以将一个文件逐字复制到另一个文件中。

void copy()
    {
        ifstream file;
        file.open("file");
        ofstream tabel;
        tabel.open("copy");
        string word;
        char x;
        x = file.get();
        while (x != ' ')
        {
            word += x;
            x = file.get();

        }
        tabel << word;
        word.clear();
        while (!file.eof())
        {
            x = file.get();
            while (x != ' ')
            {
                word += x;
                x = file.get();
            }
            tabel << word << " ";
            word.clear();
        }
    }

但是当我运行这段代码时,我的 VS 卡住了。为什么我不能写入“标签文件

我认为问题出在这里

            while (!file.eof())
            {
                x = file.get();
                while (x != ' ')
                {
                    word += x;
                    x = file.get();
                }
                tabel << word << " ";
                word.clear();
            }

解决方法

也许这可能会有所帮助:

#include <fstream>

int main() {
    std::ifstream in("file");
    std::ofstream out("copy");

    std::string word;
    while (getline(in,word,' ')) {
        out << word;
    }
}
,

这是我的回答:
在运行此代码之前,您必须在项目文件夹中创建 file.txt。代码已注释。

void copy()
        {
            std::fstream file("file.txt");//open file
            
            std::ofstream tabel("copy.txt");//open tabel
        
            std::string word = "";
        
            while (file)
            {
                file >> word;//read until space(word by word)
                tabel << (word + " ");//add word to tabel
                word = "";
            }
            //closing files
            file.close();
            tabel.close();
        }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。