尝试验证数据时内部有些奇怪

我正在尝试执行while循环,以验证数据!收到错误数据时应再次询问。但是,如果错误的数据得到程序,则会跳过cin >> a;

再次循环

以下是我已经尝试过的两个验证码:

第一个[Pic of console]

int a;

do
{
  a = NULL;
  cout << "Press some number: ";       
  cin >> a;

} while (a>=0 || a<=0);

第二个:[Pic of console]

int a;

do
{
  cin.clear();    cin.sync();

  cout << "give me number: ";   cin >> a;

} while (cin.fail());
zhenhao1986 回答:尝试验证数据时内部有些奇怪

这样,您可以检查输入的数字是否为数字:

int a;
bool flag=false;
while (true)
{
    flag=false;
    std::string input;
    std::cout << "Press some number: ";
    std::getline(std::cin,input);
    try
    {
        a = stoi(input);
    }
    catch(const std::exception& e)
    {
        std::cout <<"Invalid number" << std::endl;
        flag=true;
    }
    if (!flag)
        break;

还有其他方法可以做到这一点,但是我并没有把向量或其他东西弄乱了。

本文链接:https://www.f2er.com/3128314.html

大家都在问