簡體   English   中英

c:如何使用 sscanf 讀取命令行參數 (x,y) 並將 x 和 y 作為單獨的雙精度值存儲在結構中?

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

我正在研究一個復數計算器。 用戶必須使用命令行將復雜操作數作為 arguments 傳遞給主 function。 此外,數字需要准確地以這種表示法(x,y)傳遞,其中 x 是數字的實部,y 是虛部。

我為復數創建了一個結構。 我相信我必須使用 sscanf 從 argv 讀取並將值存儲到我的結構復雜變量的相應實部和虛部(它將保存要操作的數字),但我無法實現它,尤其是在使用括號格式時。

目前,我專注於能夠從命令行參數中存儲至少一個復數。 我希望這里有人能引導我朝着正確的方向前進。 這是我的代碼部分,它處理從 argv 讀取並存儲在我的 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;
}

我嘗試在sscanf的參數中使用不同的變體,但到目前為止,我只成功存儲了一個雙精度數(對應於數字的實數部分),並且僅在用戶不使用括號時. 我該如何進行?

我認為最好將參數讀取為整個字符串(%s)然后處理它。 但如果你堅持使用 sscanf 你可以嘗試使用它。

但請記住,當您傳遞 (1,2) 之類的參數時,類似的命令會認為它是一個參數,因此您需要傳遞 (1, 2) 之類的東西 - 它在逗號和 2 之間有空格。也不要忘記檢查您是否有 3 個參數。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM