简体   繁体   中英

How to check if last command line argument is a valid digit - C programming

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.

ORIGINAL

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:

  1. Check the length of the string ( argv[argc-1][1] == '\0' );
  2. Check if the first character is a digit character ( 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);
}

EDIT #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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM