错误的字符串类型转换为unsigned int [英] Malfunctioning type-casting of string to unsigned int
问题描述
我写了一个C ++函数有一个恼人的问题,其目的是验证用户输入。该函数读取用户输入,验证它是否是一个数字,如果是,则是否在[min,max]范围内。
I'm having a annoying problem with a C++ function that I wrote and whose purpose is to validate de user input. The function reads the user input, verifies if it's a number and, if so, if it is in the range [min, max].
模板函数使用无符号类型,如 size_t
,输入是负数。字符串流将字符串转换为类似4294967291.我可以看到,程序正在将数据转换为接近无符号数据类型的最大值(在numeric_limits头中定义)的值,但我的问题是为什么,因为 if
语句应停止在 sstream>> value
?
The problem occurs when I invoke the template function with a unsigned type, like size_t
, and the input is a negative number. The string stream converts the string to something like 4294967291. I can see that the program is converting the data to a value near de maximum value of the unsigned data type (defined in the numeric_limits header) but my question is why, since the if
statement should stop at sstream >> value
?
我的代码:
template <class T>
T getNumberInput(std::string prompt, T min, T max) {
std::string input;
T value;
while (true) {
try {
std::cout << prompt;
std::cin.clear();
std::getline(std::cin, input);
std::stringstream sstream(input);
if (input.empty()) {
throw EmptyInput<std::string>(input);
} else if (sstream >> value && value >= min && value <= max) {
std::cout << std::endl;
return value;
} else {
throw InvalidInput<std::string>(input);
}
} catch (EmptyInput<std::string> & emptyInput) {
std::cout << "O campo não pode ser vazio!\n" << std::endl;
} catch (InvalidInput<std::string> & invalidInput){
std::cout << "Tipo de dados inválido!\n" << std::endl;
}
}
}
谢谢您的时间!
推荐答案
在包含无符号
值位,保证为模2 ^ n 。这意味着通过加上或减去2 ^ em em n的适当的倍数,任何结果被回绕到范围0到2 ^ n em -1中。这也是在C。
In C++ arithmetic involving an unsigned
type with n value bits, is guaranteed to be modulo 2^n. That means any result is wrapped back into the range 0 through 2^n-1, by adding or subtracting a suitable multiple of 2^n. This is so also in C.
所以你需要检查输入的减号,或添加一些其他检查。
So you need to check the input for minus sign, or add some other check.
顺便说一句,如果与
>>
和& &
对我的坏码仪产生了一些影响。我永远不会记得>>
与&&
的运算符优先级。我想如果它编译它一定是OK,但是,因为>>
不能取右侧的值。检查...确定,但我会使用括号来澄清这一点。
By the way, your if
with >>
and &&
produced some effect on my bad-code-meter. I can never remember the operator precedences for >>
versus &&
. I guess if it compiled it must be OK, though, since >>
can't take a value right-hand-side. Checking... OK, but I'd use parentheses to clarify that.
此外,在代码结构上,从检查输入。例如,您可以使用编辑字段中的输入在GUI程序中使用任何该代码吗?不,不是因为...
Also, on the code structure, it would be a good idea to separate the interactive input thing from the checking of the input. E.g., can you use any of that code in a GUI program, with input from an edit field? No, not as it is...
干杯& hth。,
Cheers & hth.,
这篇关于错误的字符串类型转换为unsigned int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!