gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:39:28 26 4
gpt4 key购买 nike

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

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

要测试的示例 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com