Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

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 
", 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?

question from:https://stackoverflow.com/questions/65875417/c-how-to-use-sscanf-to-read-the-command-line-argument-x-y-and-store-x-and-y-a

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 
", c.real, c.imag);
        }
        return 0;
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...