C++ 手动将字符转换为int-奇怪的行为
我编写了一个小程序,将字符转换为int。该程序读入C++ 手动将字符转换为int-奇怪的行为,c++,C++,我编写了一个小程序,将字符转换为int。该程序读入'1234'格式的字符,然后输出int1234: #include <iostream> using namespace std; int main(){ cout << "Enter a number with as many digits as you like: "; char digit_char = cin.get(); // Read in the first char int num
'1234'
格式的字符,然后输出int1234
:
#include <iostream>
using namespace std;
int main(){
cout << "Enter a number with as many digits as you like: ";
char digit_char = cin.get(); // Read in the first char
int number = digit_char - '0';
digit_char = cin.get(); // Read in the next number
while(digit_char != ' '){ // While there is another number
// Shift the number to the left one place, add new number
number = number * 10 + (digit_char - '0');
digit_char = cin.get(); // Read the next number
}
cout << "Number entered: " << number << endl;
return 0;
}
#包括
使用名称空间std;
int main(){
coutTypeint
不够宽,无法存储如此大的数字。请尝试使用无符号长整型int
而不是Typeint
您可以检查给定整数类型中可以表示的最大数
#include <iostream>
#include <limits>
int main()
{
std::cout << std::numeric_limits<unsigned long long int>::max() << std::endl;
}
#包括
#包括
int main()
{
std::cout12345678901在二进制中为34位。因此,您溢出了整数值并设置了符号位。请尝试对变量数字使用无符号长整型int
,而不是使用int
。
这应该可以解决您的问题。溢出整数。使用无符号长整型。系统上的int
大小是多少,系统上int
可以容纳的最大值是多少?提示:整型中可以存储的最大数字是多少?它不应该再“奇怪”了