最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c++ - How to flush a stream in C++23 when using std::print or std::println? - Stack Overflow

programmeradmin4浏览0评论

I am using the new C++23 std::print function from the <print> utility.

My understanding is that the C++ standard does not define whether or not std::print and std::println should flush the stream after writing to it.

If I wanted to flush the stream (stdout or stderr), what is the most appropriate solution in C++ 23?

I am using the new C++23 std::print function from the <print> utility.

My understanding is that the C++ standard does not define whether or not std::print and std::println should flush the stream after writing to it.

If I wanted to flush the stream (stdout or stderr), what is the most appropriate solution in C++ 23?

Share Improve this question edited Jan 31 at 18:57 prapin 6,8685 gold badges29 silver badges54 bronze badges asked Jan 26 at 22:18 user2138149user2138149 16.8k30 gold badges145 silver badges287 bronze badges 9
  • 1 Not sure, but I'd guess std::fflush(stdout); – Ted Lyngmo Commented Jan 26 at 22:22
  • @Rud48 that's my question from a year ago – user2138149 Commented Jan 27 at 8:16
  • then why are you asking this again? – Christoph Rackwitz Commented Jan 27 at 12:31
  • 1 @ChristophRackwitz See the problem with responses like this is you come in here assuming this is some kind of reputation bump. The reality of what happened is I recalled my question from some time ago, and when I looked at it my interpretation was it was not conclusive as to how std::print/std::println should be flushed in C++23. That's why I explicitly asked what is the most appropriate solution in C++ 23? Because it was not clear to me and although there was a solution embedded inside an answer to my previous question, this was a different question... – user2138149 Commented Jan 27 at 13:10
  • 1 Even if so, your self-answer doesn't provide any new information. The answers in that thread already suggest both std::flush and std::fflush. And if anything, they explain in more detail the difference between them. – HolyBlackCat Commented Jan 27 at 14:09
 |  Show 4 more comments

2 Answers 2

Reset to default 0

Use one of

std::flush

which flushes a std::basic_ostream

or

std::fflush

which operates on a FILE*.

Detailed references can be found below

  • https://en.cppreference.com/w/cpp/io/manip/flush
  • https://en.cppreference.com/w/cpp/io/c/fflush
#include <cstdio>
#include <iostream>
#include <print>

int main()
{
    std::println(stdout, "One");
    std::fflush(stdout);

    std::println(std::clog, "Two");
    std::flush(std::clog);
}
发布评论

评论列表(0)

  1. 暂无评论