Checking to make sure argv[1] is an integer c++

Ryan Mann picture Ryan Mann · Apr 22, 2013 · Viewed 8.4k times · Source

For my program I have to make sure the user only inputs a positive INTEGER. for example if the user inputted 12hi it should not run the program and print to std error. I am not quite sure how to implement this.

int main(int argc, char *argv[])   
{ 
    if(atoi(argv[1]) < 1)
    {
        cerr << "ERROR!"<< endl;
        return 1;
    }
    return 0;
}

Answer

hmjd picture hmjd · Apr 22, 2013

Pass it to a std::istringstream and ensure all data was processed:

if (a_argc > 1)
{
    std::istringstream in(a_argv[1]);
    int i;
    if (in >> i && in.eof())
    {
        std::cout << "Valid integer\n";
    }
}

See online demo at http://ideone.com/8bEYJq.