I'm writing a program that takes a single command line argument. This argument needs to be in the range [0, INT_MAX]. What is the best way to take argv[1] and convert it into an int, while ensuring that it will be a valid integer?
Asked
Active
Viewed 912 times
1 Answers
4
argv[1]
is the first commandline arg and strtoul() converts to an unsigned integer
Also argc is the number of arguments, so check it is at least 2 (argc counts the program name) before calling argv[1]
Strictly strtoul() is c++ but most c compilers support it in their standard library, it takes a 'c' style char * string

Martin Beckett
- 94,801
- 28
- 188
- 263
-
1
-
@the first arg as far as argc is concerned is the program name - will try and make it clear – Martin Beckett Apr 25 '11 at 02:18
-
-
`strtoul()` was in C89 before it was in C++. If you're being really thorough, you'd have to check rather carefully for the error returns from any of the `strtoX()` families of functions, probably using a wrapper function. – Jonathan Leffler Apr 25 '11 at 02:29