簡體   English   中英

c - 如何將命令行 arguments 重定向到 function?

[英]c - How do I redirect command-line arguments to a function?

我正在學習 CS50 課程,在下面的 function 中,我編寫了一組代碼來檢查用戶輸入的命令行參數是否有效。 我決定將此歸類為 function,因為它占用了我主要代碼的很大一部分。

但是,我不確定如何將命令行 arguments 實際分配給 function。 這是代碼:

#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

int valid(int a,string mystring);

int main(int argc, string argv[])
{
    valid(argc, argv[]);
}

int valid(int a, string mystring)
{
    if (a == 2)
    {
        int j = 0;
        int n = strlen(mystring[1]);
        for (int i = 0; i < n; i++)
        {
            if (isalpha(mystring[1][i]) == false)
            j++;
        }
        if (j == 0)
        {
            if (n == 26)
            {
                printf("Success.\n");
                return 1;
            }
            else
            {
                printf("Key must contain 26 characters.\n");
                return 0;
            }
        }
        else
        {
            printf("Usage: ./substitution key\n");
            return 0;
        }
    }
    else
    {
        printf("Usage: ./substitution key\n");
        return 0;
    }
}

嘗試編譯時收到以下錯誤消息。

substitution.c:10:22: error: expected expression
    valid(argc, argv[]);
                     ^
substitution.c:18:24: error: incompatible integer to pointer conversion passing 'char' to parameter of type 'const char *'; take the address with & [-Werror,-Wint-conversion]
        int n = strlen(mystring[1]);
                       ^~~~~~~~~~~
                       &
/usr/include/string.h:384:35: note: passing argument to parameter '__s' here
extern size_t strlen (const char *__s)
                                  ^
substitution.c:21:36: error: subscripted value is not an array, pointer, or vector
            if (isalpha(mystring[1][i]) == false)
                        ~~~~~~~~~~~^~
/usr/include/ctype.h:190:32: note: expanded from macro 'isalpha'
# define isalpha(c)     __isctype((c), _ISalpha)
                                   ^
/usr/include/ctype.h:89:31: note: expanded from macro '__isctype'
  ((*__ctype_b_loc ())[(int) (c)] & (unsigned short int) type)

我可以進行哪些更改,以便我的valid function 將采用命令行 arguments?

您的錯誤出現是因為您的 function 接受字符串作為參數。 但是, string argv[]不是字符串。 相反,它是一個字符串數組。 因此,錯誤消息本質上是告訴您必須向strlen傳遞一個字符串。 但是,由於您的 function 接受字符串作為參數,因此mystring[1]的計算結果為char

要解決此問題,您需要更改 function 定義以接受字符串數組,而不僅僅是一個字符串。

暫無
暫無

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

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