user78655
user78655

Reputation: 289

Manually converting a char to an int - Strange behaviour

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?

Upvotes: 2

Views: 86

Answers (4)

maxadorable
maxadorable

Reputation: 1284

Overflowed integer. Use unsigned long long int.

Upvotes: 0

abhiarora
abhiarora

Reputation: 10430

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

Upvotes: 1

sabbahillel
sabbahillel

Reputation: 4425

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

Upvotes: 3

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

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>

Upvotes: 1

Related Questions