I need to get an argument and convert it to an int. Here is my code so far:
#include <iostream>
using namespace std;
int main(int argc,int argvx[]) {
int i=1;
int answer = 23;
int temp;
// decode arguments
if(argc < 2) {
printf("You must provide at least one argument\n");
exit(0);
}
// Convert it to an int here
}
Since this answer was somehow accepted and thus will appear at the top, although it's not the best, I've improved it based on the other answers and the comments.
The C way; simplest, but will treat any invalid number as 0:
The C way with input checking:
The C++ iostreams way with input checking:
Alternative C++ way since C++11:
All four variants assume that
argc >= 2
. All accept leading whitespace; checkisspace(argv[1][0])
if you don't want that. All exceptatoi
reject trailing whitespace.The approach with istringstream can be improved in order to check that no other characters have been inserted after the expected argument:
std::stoi from string could also be used.
As WhirlWind has pointed out, the recommendations to use
atoi
aren't really very good.atoi
has no way to indicate an error, so you get the same return fromatoi("0");
as you do fromatoi("abc");
. The first is clearly meaningful, but the second is a clear error.He also recommended
strtol
, which is perfectly fine, if a little bit clumsy. Another possibility would be to usesscanf
, something like:note that
strtol
does give slightly more detailed results though -- in particular, if you got an argument like123abc
, thesscanf
call would simply say it had converted a number (123), whereasstrtol
would not only tel you it had converted the number, but also a pointer to thea
(i.e., the beginning of the part it could not convert to a number).Since you're using C++, you could also consider using
boost::lexical_cast
. This is almost as simple to use asatoi
, but also provides (roughly) the same level of detail in reporting errors asstrtol
. The biggest expense is that it can throw exceptions, so to use it your code has to be exception-safe. If you're writing C++, you should do that anyway, but it kind of forces the issue.Take a look at strtol(), if you're using the C standard library.
Note that your
main
arguments are not correct. The standard form should be:or equivalently:
There are many ways to achieve the conversion. This is one approach: