Quantcast
Viewing all articles
Browse latest Browse all 4

Answer by ssinfod for Command Line Argument

Your problem is with this line:

else if (argc == 3 && argc == testscore) {

In fact, when argc == 3, then you want to check if argv[2] is a numeric argument.

else if ( (argc==3) && (is_numeric_arg(argv[2])==1)) {

A possible implementation would be:

int is_numeric_arg(char* arg)    {        int isInt = 0;        int isFloat = 0;        int isChar = 0;        char* currChar;        int i = 0;        currChar = arg;        isInt = 1;        while (*currChar != '\0')        {            if(*currChar < '0' || *currChar > '9')            {                if(*currChar == '.'&& isInt == 1)                {                    isInt = 0;                    isFloat = 1;                }                else                {                    isInt = 0;                    isChar = 1;                }            }            currChar++;        }        if (isChar == 1){ return 0; } // argument is a string        else { return 1; } // argument is a int or float    }int main (int argc, char *argv[]) {    double testscore;    if (argc == 2) {        printf("Hello, Mr.%s.\n", argv[1]);    }    else if ( (argc==3) && (is_numeric_arg(argv[2])==1)) {        testscore = atof(argv[2]);        printf("Hi, Mr.%s, your score is %.1f\n", argv[1], testscore);    }    else  {        printf("My name is %s %s.\n", argv[1], argv[2]);    }}

I did not test the code and there is probably a better way to check that the argument from the command line is "numeric".


Viewing all articles
Browse latest Browse all 4

Trending Articles