ansi c: converting argv into int
hi i wanted to convert the argv in ansi-c into int. i am not sure of a few things...
int main(int argc, char* argv[])
let's assume my program is run as follows ./a input1 input2.
let's assume in this case that my input1 = 12345 and input2=67890
i don't want to use atoi. i wanted to convert it all by my own. for example when i call the argv[1] is it equal to only "12345" or is it possible that it may be " 12345 "? i.e. can it have spaces from any of its sides?
the problem with atoi and sscanf is that if my input1="0" and input1="abc"
then both at开发者_如何学编程oi and sscanf would return 0, if i am wrong correct me... thanks!
String-to-integer conversion in C standard library is performed by strtol
function (or other functions from strto...
group). Forget about atoi
and sscanf
- these functions provide no means for error detection and/or overflow protection.
Whether or not you may receive spaces around the argument depends on the system-specific conventions for passing leading and trailing spaces and, of course, on what was actually passed by the user. Normally, different OSes provide a way to pass these spaces if the user wants to do so. So it is really up to you to decide whether you consider such input correct or erroneous.
strtol
will essentially allow (and ignore) leading and trailing spaces. Same is true for atoi
and sscanf
.
If you really want to do this by yourself, you need to loop through the string, checking that each character is a digit. Let's assume you're using ASCII:
char *str = "624532";
int index = 0;
int value = 0;
while(str[index]) {
if(str[index] >= 48 && str[index] < 58) {
value = (value * 10) + (str[index] - 48);
}
index++;
}
Make sure you use a null-terminated string or this will run forever. It's also not going to be very helpful if your input is malformed.
How about scanf then?
精彩评论