Search code examples
c++stringintlong-integer

C++ string -> int doesn't quite work


I was given a task to code a sort of ID checker. User inputs his ID number, and it should check if it's valid and evaluate some other stuff (gender, age, etc.).

The ID number is given by user as a string, looking like this: 123456/7890

My task is to remove the '/', then convert the string to int and do some basic calculations with it e.g. if(%11==0){...}. And I got stuck on the string to int conversion.

Here is my code:

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main()
{
    string id;
    int result;
    cout << "Enter an identification number:" << endl;
    cin >> id;

    //Check if the input has "slash" on the 6th position. If so, consider the input valid and remove the slash.
    if (id.at(6) == '/')
    {
        id.erase(id.begin() +6);
    }else cout << "Invalid input." << endl;

    cout << "\n" << id << endl; //cout the ID number without the slash

    stringstream ss(id); //convert the string to int, so we can use it for calculations
    ss >> result;

    cout << "\n" <<result << endl;

    return 0;
}

This seems to work only up until certain threshold for the numbers.

As you can see here:
enter image description here

So it seems that int is too small for this. But so is long int or unsigned long int... What to do please?

Thanks in advance.


Solution

  • Use long long as equivalent for __int64. Also watch this.