【问题标题】:How to use a char from a string in main for another function?如何将主字符串中的字符用于另一个函数?
【发布时间】:2022-01-22 06:58:48
【问题描述】:

我想将两个变量传递给 C 中的函数 - 一个是字符串,另一个是字符串中的单个字符。

但是,我不确定如何在不出现“预期表达式”错误的情况下使用该函数:

int spaces_away(string cipher[], string plain[char i]);

或也出现“未声明的标识符”错误:

int spaces_away(string cipher[], char plain[i]);

我认为添加变量“i”来自代码中的“for”循环也很重要,这就是我的代码在 main 中的样子:

{
    // Error if there are not two arguments
    if (argc != 2)
    {
        printf("Command Line Must Have Two Arguments\n");
        return 1;
    }
    // Error if there are not 26 characters in encryption
    else if (strlen(argv[1]) != 26)
    {
        printf("Cipher must have 26 characters\n");
        return 1;
    }
    else
    // Takes a word and encrypts it by a user given alphabet
    {
        string stdWord = get_string("plaintext: ");
        for (int i = 0, n = strlen(stdWord); i < n; i++)
        {
                encrypt[i] = (stdWord[i] + spaces_away(argv[1], tolower(stdWord[i]));
        }
            printf("ciphertext: %s\n", (string) encrypt);
        return 0;
    }
}


【问题讨论】:

  • 这被标记为c。 C 没有内置的string 类型,你自己定义了吗?如果是这样,那将是一个答案。
  • @marco-a 这看起来很像cs50 问题。 stringchar * 并且库代码有一个 get_string 函数

标签: c parameters char typedef function-declaration


【解决方案1】:

我认为添加变量“i”来自 代码中的“for”循环

编译器在解析函数声明时,对 for 循环中的变量 i 一无所知。:)

如果第二个参数必须具有char 类型,则以这种方式声明它。例如

int spaces_away(string cipher, char c );

还是一样

int spaces_away( char *cipher, char c );

int spaces_away( char cipher[], char c );

注意,如果你使用别名string,那么第一个参数必须声明为

string cipher

而不是

string cipher[]

函数tolower应该像这样调用

tolower(( unsigned char )stdWord[i])

【讨论】:

  • 请原谅我的愚蠢问题,但为什么 tolower 需要那个演员?
  • @kirjosieppo 如果字符串将包含一个具有例如负值的字符,那么这种带有负值的 tolower 调用可能会引发未定义的行为。
  • 负值字符?这听起来很疯狂
  • @kirjosieppo Do I need to cast to unsigned char before calling toupper(), tolower(), et al.?c++ 已标记,但在这种情况下仍与 C 相关)
  • @kirjosieppo 有针对不同语言的扩展 ASCII 表。您也可以直接将负值分配给字符数组的任何元素。
猜你喜欢
  • 1970-01-01
  • 2012-10-04
  • 2021-12-06
  • 2021-06-15
  • 1970-01-01
  • 2012-08-14
  • 2012-09-25
  • 2022-10-13
相关资源
最近更新 更多