簡體   English   中英

從 C 中的字符串中獲取由空格和制表符分隔的子字符串

[英]Getting substrings separated by spaces and tabs from a string in C

我需要編寫一個從用戶那里獲取命令行的程序——命令行中的第一個詞是命令本身,rest 是命令的 arguments。 該命令和 arguments 可以由用戶想要的許多空格和制表符分隔。 例如:“Multiply ab”“Multiply”是命令,“a”和“b”是 2 個矩陣的名稱。 程序需要檢查第一個單詞是否為有效命令:

*if yes - it should check if the rest of the arguments are valid or if there are too many/less arguments for this specific command (the amount of the arguments differs between the commands).

*如果命令無效或 arguments 的編號不好 - 它應該打印相同的錯誤。

我的主要問題是我不知道如何將命令和 arguments 分開,如果它們都在同一行中,我需要對這一行中的每個命令/參數進行驗證檢查。 我嘗試對第一個單詞使用 for 循環,但效果不是很好,我不知道如何處理 arguments 的 rest。

fgets(command_line, sizeof(command_line), stdin);
        for (int i = 0; i < strlen(command_line); i++) {
            if (command_line[i] == ' ' || command_line[i] == '  ')
                position++;
        }
            while (c < strlen(command_line)) {
                command[c] = command_line[position + c];
                c++;
            }
            command[c] = '\0';

我對編程很陌生,所以我希望我的問題很清楚,我將不勝感激。 謝謝!

我不會寫像strtok()這樣的 function ,我寧願使用strtok() ,因為它可以滿足您的需求。

    #define MAX_ARGS 30  // or however many you need
    char *words[MAX_ARGS];
    int nargs = 0;
    for (char *tok, *str = command_line; tok = strtok(str, " \t\n"); str = NULL)
        if (nargs == MAX_ARGS) return 1;  // too many
        else words[nargs++] = tok;
    // now if nargs > 0, words[0] points to the command, words[1..nargs-1] the arguments

請注意,在分隔符集中包含\n是為了擺脫fgets()留下的行終止符。

暫無
暫無

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

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