etotheipi
etotheipi

Reputation: 49

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.

Upvotes: 2

Views: 161

Answers (3)

BLUEPIXY
BLUEPIXY

Reputation: 40145

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

Upvotes: 1

Fiddling Bits
Fiddling Bits

Reputation: 8861

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

Upvotes: 1

Jens
Jens

Reputation: 72737

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.

Upvotes: 2

Related Questions