繁体   English   中英

如何检查用户是否输入了整数

[英]how to check if the user input an integer

如果用户输入的是整数而不是字符或字符串,则需要检入程序。 字符并不是很糟糕,因为它通常是整数,但是如果用户输入字符序列,那么它就变得很疯狂。

我做了这个功能

int* ask_lung(int* lung)
{
int tmp; // length of a word

cout << "Inserisci la lunghezza della parola da indovinare: ";
cin >> tmp;

if(cin)
{
    // Se i è uguale a o minore di 0 allora ritorna all'inizio

    if(tmp <= 0)
    {
        cout << endl << "\tNon puoi inserire 0." << endl << endl;
        ask_lung(lung);
    }
    else
    {
                    // the error is about here, when it reaches this part of the code it keeps showing the first line "Inserisci la lunghezza della parola da indovinare: "
        *lung = tmp;
    }
}
else ask_lung(lung);

return lung;
}

如果是字符串,则流中包含大量无效字符,您需要将这些字符流刷新到新状态。 与其递归地执行此操作,不如循环执行。 这足以满足您的需求。

while(true)
{
  cout << "Please Enter an Integer" << endl ;
  if (cin >> temp)  //true if a leading integer has entered the stream
    break ;
  else
  {
    cout << "Invalid Input" << endl ;
    cin.clear() ;
    cin.ignore(std::numeric_limits<streamsize> :: max(), '\n') ;
  }
}

您可以将std::all_ofstd::isdigit一起使用:

std::string input;
std::cin >> input;

if ( std::all_of(input.begin(), input.end(), std::isdigit) )
{
     //input is integer
}

或者,如果您想测试并且也想要整数,那么最好将input用作int ,如其他答案所建议。 如果已经(读取)了字符串,则可以考虑使用std::stoi 请注意, std::stoi会在错误时引发异常。

输入已正确处理,问题在于您正在返回指向局部变量的指针。 该变量在堆栈上,一旦函数返回,它将被释放。 相反,您应该只返回整数本身,而不是指向它的指针。

编辑:我看到实际上您不是在返回指向整数的指针,而是将其分配给指针所指向的整数。 不过,最好只返回整数本身。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM