Manually converting a char to an int - Strange behaviour

时间:2016-04-04 16:34:18

标签: c++

I've wrote a small program to convert a char to an int. The program reads in chars of the form '1234' and then outputs the int 1234:

#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;
}

This works fine with small chars, but if I try a big char (length 11 and above) like 12345678901 the program returns the wrong result, -539222987.

What's going on?

4 个答案:

答案 0 :(得分:3)

12345678901 in binary is 34 bits. As a result, you overflowed the integer value and set the sign bit.

答案 1 :(得分:1)

Type int is not wide enough to store such big numbers. Try to use unsigned long long int instead of the type int.

You can check what maximum number can be represented in the given integer type. For example

#include <iostream>
#include <limits>

int main()
{
    std::cout << std::numeric_limits<unsigned long long int>::max() << std::endl;
}

In C you can use constant ULLONG_MAX defined in header <limits.h>

答案 2 :(得分:1)

Instead of using int, try to use unsigned long long int for your variable number. That should solve your problem.

答案 3 :(得分:0)

Overflowed integer. Use unsigned long long int.