[英]how to check if the user input an integer
I need to check in my program if the user inputs an integer and not a character or string. 如果用户输入的是整数而不是字符或字符串,则需要检入程序。 Character isn't that bad since it's pratically an integer, but if the user enters a sequence of characters then it just goes nuts.
字符并不是很糟糕,因为它通常是整数,但是如果用户输入字符序列,那么它就变得很疯狂。
I've made this function 我做了这个功能
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;
}
In case of string of characters, your stream contains large number of invalid characters and you need to flush your stream of those characters to a new state. 如果是字符串,则流中包含大量无效字符,您需要将这些字符流刷新到新状态。 Instead of doing that recursively, it is better to do that in a loop.
与其递归地执行此操作,不如循环执行。 This would suffice for you reasonably.
这足以满足您的需求。
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') ;
}
}
You can use std::all_of
along with std::isdigit
as: 您可以将
std::all_of
与std::isdigit
一起使用:
std::string input;
std::cin >> input;
if ( std::all_of(input.begin(), input.end(), std::isdigit) )
{
//input is integer
}
Or, if you want to test and also want the integer, then it is better to use input
as int
, as suggested by other answer. 或者,如果您想测试并且也想要整数,那么最好将
input
用作int
,如其他答案所建议。 You may consider using std::stoi
if you have (read) the string already. 如果已经(读取)了字符串,则可以考虑使用
std::stoi
。 Note that std::stoi
throws exception on error. 请注意,
std::stoi
会在错误时引发异常。
The input is handled correctly, the problem is that you're returning a pointer to a local variable. 输入已正确处理,问题在于您正在返回指向局部变量的指针。 That variable is on the stack, an it will be deallocated once the function returns.
该变量在堆栈上,一旦函数返回,它将被释放。 Instead you should just return the integer itself, not a pointer to it.
相反,您应该只返回整数本身,而不是指向它的指针。
EDIT: I see that actually you're not returning a pointer to the integer, you're assigning to the integer that the pointer points to. 编辑:我看到实际上您不是在返回指向整数的指针,而是将其分配给指针所指向的整数。 Still, it's better to just return the integer itself.
不过,最好只返回整数本身。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.