C++ 输入int类型出错处理

C++ 输入int类型出错处理

#include <iostream>
#include <stdio.h>

using namespace std;

int main()
{
    int n;
    char ch;

    while (true) 
    {
        cout << "输入一个int类型的整数:";
        // 如果输入非int类型
        if (!(cin >> n)) 
        {// 清空缓冲区
            while ((ch = getchar()) != '\n')
                continue;
            // 打印错误信息
            cout << "请输入int类型!!!" << endl;
            continue;
        }

        cout << "你输入的整数为:" << n << endl;
    }    
}

猜你喜欢

转载自www.cnblogs.com/noonjuan/p/12124474.html