【问题标题】:fstream behaving weirdlyfstream 行为怪异
【发布时间】:2023-03-02 22:13:02
【问题描述】:

我是 C++ 新手,但这太荒谬了!

// fstream output;
// string func();

// both have proven to be working somewhat properly, as I got something already
// written correctly in the output file and I tested func() in the cout

output << func(); // func() returns a string;

我被写入文件:

// literally nothing

但是当我这样做时

output << "what the hell" << endl;
output << func();

我明白了

what the hell
{// expected output}
what the hell
{// expected output}
...
what the hell
// last output still missing

我不知道可能是什么问题,在这一点上,我确信该程序只是为了惹恼我。

编辑:

string func()
{
    return "test\n";
}

我也刚刚发现,只要我手动往输出里面放点东西,什么都会写,像这样:

for(int=0; i<4; i++)
{
    output << func();
}
output << endl;

找我

test
test
test
test
// func line
// endl line

【问题讨论】:

  • 请显示minimal reproducible example。闻起来像func中未定义的行为@
  • 请发布完整的minimal reproducible examplefunc() 中的实际代码是什么?
  • 嗯,您确定您使用的文本编辑器正在刷新文件更改吗?也许尝试输出
  • 我猜你使用的是旧版本的 mingw,它在退出时无法刷新 cout
  • 发布真实代码。请注意,正式地,输出流的结尾必须有一个换行符。这通常不是问题,但从问题中的各种随机码sn-ps中无法说出来。

标签: c++ file-io fstream ofstream


【解决方案1】:

正如 One Man Monkey Squad 所说,这只是不刷新 fstream 的问题。

string func()
{
   return "test"
}

output << func() << endl;

得到我想要的输出,末尾没有多余的行,超出正常的新行

【讨论】:

    猜你喜欢
    • 2019-11-03
    • 2012-08-05
    • 2012-12-03
    相关资源
    最近更新 更多