• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 109
  • Last Modified:

most elegant way to check if an argv[i] is an integer

Hello

In C++, what is the most elegant way to check if an argv[i] is an integer? I prefer a short inbuilt check instead of writing a function that does something like traverse the char* and check if each element is a digit.

Any suggestions? thank you
0
LuckyLucks
Asked:
LuckyLucks
1 Solution
 
NorieVBA ExpertCommented:
Are you assuming the argument will be numeric or could it be anything?
0
 
Fabrice LambertFabrice LambertCommented:
Hi,

You can use the std::stoi function, and see if it throw an exception:
bool isInteger(char const* in)
{
    try
    {
        std::stoi(std::string(in));
        return true;
    }
    catch(std::invalid_argument const& e)
    {
        return false;
    }
}

Open in new window

Note: This can still throw an out of range exception.
Up to you to see if that's an acceptable behavior or not.
0
 
evilrixSenior Software Engineer (Avast)Commented:
Use a regular expression: http://en.cppreference.com/w/cpp/regex
0
 
sarabandeCommented:
instead of writing a function that does something like traverse the char* and check if each element is a digit.
this check wouldn't be sufficient since you wouldn't know whether the string is a 32-bit or 64-bit integer (or even more bits).

if the check for limits is not required you could do

if (std::string(argv[i]).find_first_not_of("1234567890") != std::string::npos)
{
     // argv[i] contains at least one non-digit
     return error_handling(argv[i]);
}

Open in new window


note, the above code also would test each char element whether it is a digit or not.

Sara
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now