c++ - 需要额外的换行符

标签 c++ error-handling

#include <iostream>
using namespace std;
int main()
{
    int a;
    do
    {
        /* First reset the flag and then clean the buffer*/
        cin.ignore();
        cin.clear();
        /* Input the number from the user*/
        cout << "Enter number\n";
        cin >> a;
        /*Diplay appropiate error if the input was wrong*/
        if(cin.fail())
        {
            cout << "invalid input \n";
        }
        /*Display the number if the input was valid*/
        else
        {
            cout << "number entered is : " << a << endl;
        }
    }
    while(cin.fail());  //repeat until the input is correct
    return 0;
}

每次执行此程序时,我必须先输入一个新行,然后再执行cout<<"Enter number\n";

其背后的原因是什么,可能的解决方案是什么。

注意:如果没有cin.ignore(),程序将进入无限循环

最佳答案

   cin.ignore();
   cin.clear();
   /* Input the number from the user*/
   cout << "Enter number\n";
   cin >> a;


   /* Input the number from the user*/
   cout << "Enter number\n";

   cin.clear();
   cin.ignore();
   cin >> a;

关于c++ - 需要额外的换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16208992/

相关文章:

java - RX Java - 重试一些抛出异常的代码

c - 我的实现未能删除 c 中 String 的最后一个字符

stored-procedures - Teradata存储过程-如何从错误处理程序获取错误消息文本

c++ - 如何使用 printf 打印空白字符?

c++ - 在模板类中重载运算符 <<

C++ 映射从迭代器位置开始搜索

error-handling - 如何避免在onCompleted中引发的异常被吞下

asp.net - 未选择文件时如何显示错误

c++ - Opengl平滑着色生成对象

c++ - 方法应该将 R 值引用作为输入有任何正当理由吗?