Reputation: 27
I am trying to write a program which will check a text file, but also uses a number which is the last argument passed. I want to do some error checking to make sure that the last argument is a digit.
Upvotes: 0
Views: 522
Reputation: 416
I do not know what is the digit()
function, but whatever this function is, it will never check if the string argv[argc-1]
is a digit successfully. That is because the atoi()
function will return zero if argv[argc-1]
is not a numeric string as an error, but will also return zero if argv[argc-1]
is "0"
.
To verify if argv[argc-1]
is one and only one digit, you need to:
argv[argc-1][1] == '\0'
);isdigit( argv[argc-1][0] )
).Here is the final code.
char *a = argv[argc-1];
if ( (a[1] != '\0') || !isdigit(a[0]) ) {
printf("No valid digit entered\n");
exit(1);
}
My original answer has two problems, as some users mentioned below.
In first place, I assumed that strings in argv
cannot be empty. However, if a program is called like ./program ""
, argv[1]
is going to be an empty string.
For demonstration purpose, here is a program that prints in stdout
all argv
strings and their lengths.
/* program.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char **argv) {
for (int i = 0; i < argc; i++)
printf("strlen(\"%s\") = %zu\n", argv[i], strlen(argv[i]));
return EXIT_SUCCESS;
}
Here is the output, confirming argv[1]
is an empty string.
$ gcc -Wall -std=c99 -o program program.c
$ ./program ""
strlen("./program") = 9
strlen("") = 0
$
The second problem is related to the usage of isdigit()
function. According to the manual (man isdigit
on terminal), the argument passed to isdigit()
must me an unsigned char
.
int isdigit(int c);
These functions check whether c, which must have the value of an unsigned char or EOF, falls into a certain character class according to the specified locale.
Here is the final solution without the problems mentioned in the comments below.
char *a = argv[argc-1];
if ( !isdigit((unsigned char) a[0]) || (a[1] != '\0') ) {
printf("No valid digit entered\n");
exit(1);
}
Upvotes: 2