【问题标题】:I want to make a code that the user must input integer but if the user input string it will show the "Enter Integer: "我想编写一个用户必须输入整数的代码,但如果用户输入字符串,它将显示“输入整数:”
【发布时间】:2020-05-12 07:04:44
【问题描述】:

这是我的代码,但它不起作用。如果用户输入字符串显示“Enter Integer”但显示错误,我想制作。任何人都可以帮助我吗?谢谢 整数选择;

cout << "Please enter desired number: " ;

cin  >> choice;

while (!cin)
{
    if (!cin )
    {
        cout << "ENTER INTEGER: ";
        cin.clear();
        cin.ignore(numeric_limits<streamsize> :: max(), 'n');
        cin >> choice;
        continue;
    }
    else
    {
        break;
    }
}

【问题讨论】:

    标签: c++ arrays loops data-structures


    【解决方案1】:
    int main()
    {
      cout<<"enter a number";
      int number;
      while(!(cin>>number)){
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        cout<<"enter an number\n";
      }
      cout<<number<<'\n';
    }
    

    【讨论】:

    • 此代码将帮助您在不使用 break 语句的情况下退出循环。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-17
    • 2020-08-09
    • 1970-01-01
    • 2013-09-28
    • 1970-01-01
    相关资源
    最近更新 更多