简体   繁体   中英

c: How to use sscanf to read the command-line argument (x,y) and store x and y as separate doubles inside a struct?

I'm working on a complex numbers calculator. The user must pass the complex operands as arguments to the main function using the command line. Additionally, the numbers need to be passed exactly in this notation (x,y) , where x is the real part of the number and y the imaginary part.

I created a struct for complex numbers. I believe I have to use sscanf to read from argv and store the values into the corresponding real and imaginary parts of my struct complex variables (which will hold the numbers to be operated on), but I haven't been able to achieve it, especially not when the parenthesis formatting is used.

For the moment I am focusing on being able to store at least one complex number from the command line argument. I'm hoping someone here can lead me in the right direction. Here's the portion of my code that deals with reading from argv and storing in my struct complex variable struct complex c

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


struct complex {
    double real;
    double imag;
};

int main(int argc, char *argv[]) {

    struct complex c;
    sscanf(argv, "(%lf,%lf)", &c.real, &c.imag);
    printf("%.2lf %.2lf \n", c.real, c.imag);
    return 0;
}

I've tried using different variations in the parameters of sscanf , but so far I've only succeeded at storing one of the doubles (the one corresponding to the real part of the number) and only when the user doesn't use the parenthesis. How do I procede?

I think it better to read the parameter as whole string (%s) and then process it. but if you insist using sscanf you may try to use this.

but bear in mind that when you pass parameter like (1,2) the command like will think it is one parameter so you need to pass something like (1, 2) - it have space between comma and the 2. also don't forget to check that you have 3 parameters.

   struct complex 
   {
        double real;
        double imag;
   };
    
   int main(int argc, char *argv[]) 
   {
    
        struct complex c;
        if(3 == argc)
        {
            sscanf(argv[1], "(%lf,", &c.real);
            sscanf(argv[2], "%lf)",  &c.imag);
            printf("%.2lf %.2lf \n", c.real, c.imag);
        }
        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