【问题标题】:getline doesn't work after fflushfflush 后 getline 不起作用
【发布时间】:2015-04-17 13:23:25
【问题描述】:
#include <iostream>
#include <string>
using namespace std;

int main(){
    int num;
    string str;

    cout << "Input an integer a= ";
    cin >> num;
    cout << num << endl;
    cout << "Input a string str= ";
    fflush(stdin);
    getline(cin,str);
    cout << str << endl;
    cout << "End program" << endl;
    return 0;
}

输出:

Input an integer a= 1
1
Input a string str= 
End program

fflush() 之后的getline 不起作用。

【问题讨论】:

  • 我不知道答案,但这不完全是 getline() 问题。如果不先阅读num,getline() 就可以了。
  • 尝试使用getchar(); 而不是fflush(stdin);
  • @Cool Guy:谢谢,伙计 :)
  • 不知道为什么这个问题会出现在审核队列中,但我做了一些修复以将其排除。

标签: c++ xcode getline


【解决方案1】:

fflush(stdin) 是未定义的行为,因为 fflush() 的行为仅针对输出流定义。此外,这是一个“C 风格”函数,不应与 C++ 控制台 I/O 结合使用。

您可以通过在之前的 cin 调用之后直接添加 cin.get() 来丢弃换行符,而不是 fflush():

cin >> num;
cin.get();

【讨论】:

    【解决方案2】:

    当程序提示您“输入整数 a=”时,您键入 1 并 Enter,因此在 cin &gt;&gt; num; 之后,流中会保留一个换行符。然后新行将分配给str。这就是为什么您认为fflush 之后的getline(正如伦丁的回答所说,fflush(stdin) 是未定义的行为)不起作用。

    getline 之前使用cin.ignore(A_BIG_NUM, '\n'); 忽略新行。

    【讨论】:

      猜你喜欢
      • 2012-02-25
      • 1970-01-01
      • 2017-06-04
      • 2012-12-27
      • 1970-01-01
      • 1970-01-01
      • 2013-10-15
      • 1970-01-01
      • 2015-06-26
      相关资源
      最近更新 更多