【问题标题】:c - How do I redirect command-line arguments to a function?c - 如何将命令行参数重定向到函数?
【发布时间】:2020-12-29 00:35:25
【问题描述】:

我正在学习 CS50 课程,在下面的函数中,我编写了一组代码来检查用户输入的命令行参数是否有效。我决定将其归为一个函数,因为它占用了我的主要代码的很大一部分。

但是,我不确定如何将命令行参数实际分配给函数。代码如下:

#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 函数接受命令行参数?

【问题讨论】:

  • 函数参数应该与main中的相同,即int valid(int argc, string argv[]) 然后像这样调用函数:valid(argc, argv)
  • @user3386109 是的,修复了它。我之前试过,它给了我一个错误,所以我在定义它时一定是打错了。非常感谢!
  • strlen 将字符串作为参数,但您将单个字符传递给它,另一件事,您想以C 样式或C++ 创建它?因为您使用的是C++ 字符串,但您甚至没有包含字符串。
  • @AriaN 这不是 C++ 字符串。它是 cs50.h 中 char[] 的 typedef。如果你问我,这只会让学生感到困惑。
  • @IvanC 也让我很困惑,谢谢告知。

标签: c command-line command-line-arguments cs50


【解决方案1】:

您的错误出现是因为您的函数接受字符串作为参数。但是,string argv[] 不是字符串。相反,它是一个字符串数组。因此,错误消息本质上是告诉您必须传递strlen 一个字符串。但是,由于您的函数接受字符串作为参数,mystring[1] 的计算结果为 char

要解决此问题,您需要更改函数定义以接受字符串数组,而不仅仅是一个字符串。

【讨论】:

    猜你喜欢
    • 2019-12-12
    • 2013-12-23
    • 2010-11-28
    • 2020-10-05
    • 2010-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-28
    相关资源
    最近更新 更多