使用整数变量检查用户输入是整数还是字符串 [英] check whether the user input is integer or string using integer variable
问题描述
我需要检查用户是否输入了整数,如1,15,-1或像2bda或5afnd等字符串。可以很容易地通过使用一个字符串来完成。
i need to check whether user has entered an integer like 1,15,-1 or a string like 2bda or 5afnd etc. It can easily be done by using a string of characters.
可以使用c或c ++中的int变量吗?
can it be done using an int variable in c or c++?
推荐答案
否, int
不能存储任意字符串。
No, int
cannot store an arbitrary string of characters.
int
整数类型,其值在一些最小值和最大值之间,取决于实现定义的大小。在整数中没有错误状态或错误值(与具有非数字值 NaN
的浮点类型不同)。但是,您可以选择无效的值(通常为最小值或最大值),或者如果只有正值,则为负值。然后,您可以在处理之前检查该值。例如:
int
is a signed integral type that holds values between some min and max value, depending on the implementation-defined size. There is no error state or error value built into the integer (unlike floating point types which have a Not a Number value, NaN
). However, you can choose values that are invalid, commonly the min or max value, or a negative value if only positive values are expected. Then you can check for that value before you process. For example:
#include <climits> // for INT_MIN
bool is_valid( int value )
{
return value != INT_MIN;
}
int get_value( const std::string& str_value )
{
std::istringstream ss( str_value );
int value;
if( ss >> value )
return value;
else
return INT_MIN;
}
void print_if_valid( int value )
{
if( is_valid( value ) )
std::cout << value << std::endl;
else
std::cout << "invalid" << std::endl;
}
int main()
{
int num1 = get_value( "2" );
int num2 = get_value( "a" );
print_if_valid( num1 );
print_if_valid( num2 );
return 0;
}
请注意,使用此解决方案,如果值实际上 INT_MIN
(如果 int
是32位,这将是-2147483648),它仍将被视为无效,即使它是有效的 int
。
Note that with this solution, if the value is actually INT_MIN
(if int
is 32 bit than this will be -2147483648), it will still be treated as invalid even though it was a valid int
.
这篇关于使用整数变量检查用户输入是整数还是字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!