简体   繁体   English

如何在 C++ 中使用 fflush(stdin)

[英]How to use fflush(stdin) in C++

I have a simple question (I think so) about fflush() in C++.我有一个关于 C++ 中的fflush()的简单问题(我想是的)。 Every time I write some code to input string in C++, I have to try many many ways because My program caused Error every time.每次我写一些代码在 C++ 中输入字符串时,我都必须尝试很多方法,因为我的程序每次都会导致错误。 So I will ask a very simple question.所以我会问一个非常简单的问题。 My code here:我的代码在这里:

void main()
{
    int n;
    string str;
    cin >> n;
    fflush(stdin);
    fflush(stdin);
    getline(cin, str);
    cout << n << endl << str << endl;
}

and the compiler does not allow me to enter the string str , how can I do that now?并且编译器不允许我输入字符串str ,我现在该怎么做?

And I don't want to talk about cin.ignore() here, just about only fflush()而且我不想在这里谈论cin.ignore() ,只是fflush()

flushing stdin is undefined behavior, since fflush is meant to be called on an output stream.刷新stdin是未定义的行为,因为 fflush 意味着在 output stream 上调用。 This is taken from the C standard [7.21.5.2]/2 :这取自 C 标准[7.21.5.2]/2

 int fflush(FILE *ostream);

If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.否则,行为未定义。

you can find the standard C here in the link below, go to page 139您可以在下面的链接中找到标准 C,go 到第 139 页

ANSI/ISO 9899-1990 ANSI/ISO 9899-1990

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM