c++ - 标准输出和标准输入关系

标签 c++ c

<分区>

Possible Duplicate:
Does reading from stdin flush stdout?

C++ 标准保证在下次调用 std::cin 之前打印缓冲区中包含的所有数据。像这样:

#include <iostream>

void bar()
{
    int x;
    std::cout << "Enter an integer: "; /* 1 */
    std::cin >> x; /* 2 */
}

因为这个:

ISO/IEC 14882:2011

27.4.2 Narrow stream objects [narrow.stream.objects]

2 After the object cin is initialized, cin.tie() returns &cout. Its state is otherwise the same as required for basic_ios::init (27.5.5.2).

27.4.3 Wide stream objects [wide.stream.objects]

2 After the object wcin is initialized, wcin.tie() returns &wcout. Its state is otherwise the same as required for basic_ios::init (27.5.5.2).

但在 C 中,真的不能保证在任何尝试 stdin 之前都会打印 stdout 缓冲区中包含的所有内容吗?

#include <stdio.h>

void bar()
{
    int x;
    printf("Enter an integer: "); /* 1 */
    scanf("%d", &x); /* 2 */
}

我知道 stdout 是行缓冲的,但我不想在这种情况下放置 '\n' 字符。使用 fflush/fclose/etc 是在 C 中输入请求之前获得输出的唯一正确方法吗?

最佳答案

不,没有这样的保证。 是的,您可以使用 fflush() 来确保刷新标准输出。

这个问题密切相关:Does reading from stdin flush stdout?

关于c++ - 标准输出和标准输入关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12130000/

相关文章:

c++ - 程序崩溃

c++ - 我如何使用 boost::test 和 xcode 4 来测试一些 ios c++ 代码?

c - POSIX 套接字 : How to detect Ctrl-C sent over Telnet?

c - getopt 跨平台兼容性

c++ - 当 T = int& 时,为什么构造函数 Message(const T& data) 与 Message(T&& data) 冲突?

c++ - linux C++ 应用程序部署

c - 如何删除包含后的声明

c - 变量声明问题

c - 如何检查数组是否有回车

c++ - C++ 中非成员函数的广义链接