In college I was asked if our program detects if the string enter from command line arguments is a integer which it did not(./Program 3.7
). Now I am wondering how I can detect this. So input as for example a
is invalid which atoi detects, but input like for example 3.6
should be invalid but atoi will convert this to an integer.
#include <stdio.h>
int main(int argc, char *argv[]) {
if (argc > 1) {
int number = atoi(argv[1]);
printf("okay\n");
}
}
But offcourse okay should only be printed if argv[1] is really an integer. Hope my question is clear. Many thanks.
Have a look at strtol.
If endptr is not NULL, strtol() stores the address of the first invalid character in *endptr. If there were no digits at all, however, strtol() stores the original value of str in *endptr. (Thus, if *str is not
\0' but **endptr is
\0' on return, the entire string was valid.)
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if (argc > 1) {
char* end;
long number = strtol(argv[1], &end, 0);
if (*end == '\0')
printf("okay\n");
}
}
Assuming you want to know how it could be done in code (possible if it is indeed homework), one way is to think about what constitutes an integer in terms of the string. It would most likely be:
From that specification, you can write a function that will do the work for you.
Something like this pseudo-code would be a good start:
set sign to +1.
set gotdigit to false.
set accumulator to 0.
set index to 0.
if char[index] is '+':
set index to index + 1.
else:
if char[index] is '-':
set sign to -1.
set index to index + 1.
while char[index] not end-of-string:
if char[index] not numeric:
return error.
set accumulator to accumulator * 10 + numeric value of char[index].
catch overflow here and return error.
set index to index + 1.
set gotdigit to true.
if not gotdigit:
return error.
return sign * accumulator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With