简体   繁体   中英

processing/parsing command line arguments in C

I have written the next simple program

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
   if (argc<2) {
       return 0;
   }
   else {
       double x = atof(argv[1]);
       printf ("%f\n", x);
       return 0;
   }
}

For example

./test 3.14

outputs

3.140000

Now I am trying to use this program with some other program, which gives outputs of the following form:

[3.14

Or just some other symbol in front of 3.14, but not a number. I want to use this output as input for the simple program I just showed, obviously I can't just pass this as an argument. My question is therefore how to accomplish this. I thought a lot about this problem, and tried to search the internet, but this is such a specific problem, I couldn't find answers. Thanks in advance.

You may use sscanf instead of atof to do a simple parse of a not-too-complicated string:

 double x;

 if (sscanf (argv[1], "[%lf", &x) == 1) {
     printf ("found a [ followed by %f\n", x);
 }
 else {
     printf ("hmm, '%s' didn't look like a [ followed by a double value\n", argv[1]);
 }

Please refer to your friendly scanf (or sscanf ) manual page for details of the possibilities to parse various items.

How about something like this:

char *str = argv[1] + 1
float pi = atof(str);
printf("%f\n", pi);

Or, if you don't know how many non-digits will lead the number:

char *str = NULL;

for(int i = 0; i < strlen(argv[1]); i++)
{
    if(isdigit(*(argv[1] + i)))
    {
        str = argv[1] + i;
        break;
    }
}

if(str)
{
    float pi = atof(str);
    printf("%f\n", pi);
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int main(int argc, char *argv[]){
    if(argc < 2)
        return 1;
    char *temp = malloc(strlen(argv[1])+1);
    char *d, *s;
    for(d=temp, s=argv[1]; *s ; ++s){
        if(isdigit(*s) || *s == '.' || *s == '-'){//cleaning
            *d++ = *s;
        }
    }
    *d = '\0';
    char *endp;
    double x = strtod(temp, &endp);
    if(*endp == '\0')
        printf("%f\n", x);
    free(temp);

    return 0;
}

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