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.

Upvotes: 0

Views: 222

Answers (3)

Necronomicron
Necronomicron

Reputation: 1310

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

Upvotes: 1

Dario Digiuni
Dario Digiuni

Reputation: 31

If you use unsigned long long int you can have up to 18446744073709551615.

Check the maximum you can get on your platform with ULLONG_MAX in .

Upvotes: 0

06needhamt
06needhamt

Reputation: 1605

Use the long long datatype as int and long are the same size

Upvotes: 0

Related Questions