c++ - 在 C++ 中流入和流出文本文件

标签 c++

基本上,我试图将相同的信息流式传输到一个文本文件中,并将相同的信息流式传输到另一个文本文件中。

但是,它给了我奇怪的新行。

要测试的示例 txt:

testing this is a test to see if this actually works

hopefully!
test



test 

test

这是它在测试后给我的输出:

testing this is a test to see if this actually works
hopefully!test


test 
test

我希望输出与输入相同。但我不确定我做错了什么。已经坚持了几个小时了,哈哈。

这是我的代码:

string input, name, content;
cout << "Enter input name and extension (Example: hi.txt)\n";
cin >> input;

ifstream file (input.c_str());

if (file.is_open()) {
    cout << "Enter output name and extension (Example: hi2.txt)\n";
    cin >> name;

    ofstream output(name.c_str());

    while (getline(file, content)) {
        output << content;

        if (content == "") {
            output << "\n";
        }
    }
}

最佳答案

std::getline 忽略分隔符,在读取一行时默认为 \n。所以,当它读到

testing this is a test to see if this actually works\n

content 实际上是

testing this is a test to see if this actually works

注意缺少的换行符。这就是为什么每一行之后都少了一个新行 :)

您必须添加被丢弃的定界符:

output << content << '\n'; //Adds the discarded '\n' delimiter

关于c++ - 在 C++ 中流入和流出文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38862584/

相关文章:

c++ - std::array 初始化中的大括号省略

c++ - gSoap,c++,如何在客户端应用程序中传递 soapStub 声明的参数

c++ - 使用 dt_dll 调试 LSP

c++ - ppt/pptx 转换为 html 或其他格式

c++ - 如何在 Direct3D 中构建纹理坐标变换矩阵

c++ - 为什么更新到 vector<map<int, int>> 中的 map 会失败?

c++ - 在基于 ATL 的 C++ 对话框中向复选框添加工具提示

c++:使用具有二进制函数的 boost 范围转换适配器

c++ - 如何解析从末尾开始的字符串C++

c++ - Qt应用程序中 undefined reference 错误