【问题标题】:How to concatenate and print every element of the string?如何连接并打印字符串的每个元素?
【发布时间】:2020-03-29 22:43:15
【问题描述】:
int main(int argc, string argv[]) {
    int ln = strlen (argv['\0']);
    int count = 0;
    char cipher_keyword [count+1];
    for (int i = 1; i < argc; i++) {
        for (int j = 0,  n = strlen(argv[i]); j < n; j++){
            cipher_keyword [j] = argv [i][j];
            printf("Cipher_keyword: %c\n", cipher_keyword [j]);
        }
    }
    printf("Cipher_keyword_outofLoop: %s\n", cipher_keyword);
    printf("\nCount of input string: %d\n", count);
    return 0;
}

输入是:

argv (file, arg1, arg2, arg3);

例如:

argv (file, abc defg hijkl)

现在,当我在循环中打印 cipher_keyword [j] 时,我将逐行打印字符串的每个元素(这是预期的)。我希望将其存储在cipher_keyword 中,循环外的printf 命令应该将所有元素放在一行中,没有任何空格。但是在循环外的printf 命令中,cipher_keyword 给了我[str.length][j] 的结果,即jijkl

如何使循环外的printf 命令打印所有元素,即abcdefghijkl

【问题讨论】:

  • 另外我不认为你可以做 int ln = strlen (argv['\0']);您应该在 [] 括号中传递一个 int,例如 argv[0]

标签: c++ c arrays string substring


【解决方案1】:

cipher_keyword 只分配了 1 个char。您的循环溢出了数组。所以你的代码有未定义的行为

您需要循环一次argv 以计算所需的总count,然后分配数组,然后再次循环遍历argv 以填充数组。

填充数组时,需要使用单独的索引计数器来正确访问数组元素。您正在使用内部循环的计数器,它会在处理的每个命令行参数上重置回 0。所以你正在覆盖数组元素。

您也没有告诉printf()cipher_keyword 中实际有多少chars 可用于打印,要么通过空终止cipher_keyword,要么通过将count 作为参数传递给printf()。您必须执行其中一个步骤,否则 printf() 可能会超出数组的边界并打印周围内存中的垃圾。

试试这样的:

int main(int argc, string argv[])
{
    int count = 0;
    for (int i = 1; i < argc; i++) {
        count += strlen(argv[i]);
    }

    char cipher_keyword [count+1];

    count = 0;
    for (int i = 1; i < argc; i++) {
        for (int j = 0, n = strlen(argv[i]); j < n; j++){
            cipher_keyword [count] = argv [i][j];
            printf("Cipher_keyword: %c\n", cipher_keyword [count]);
            ++count;
        }
    }

    cipher_keyword [count] = '\0';

    printf("Cipher_keyword_outofLoop: %s\n", cipher_keyword);
    // alternatively:
    // printf("Cipher_keyword_outofLoop: %.*s\n", count, cipher_keyword);

    printf("\nCount of input string: %d\n", count);

    return 0;
}

【讨论】:

  • 是的。我试着运行你的代码。但我仍然得到相同的答案,即它只打印最后一个元素的字符。我也尝试了您的替代代码 printf,但仍然是相同的答案。
  • @Indu 抱歉,我遗漏了一个重要细节。我已经按答案更新了。
猜你喜欢
  • 2017-03-04
  • 1970-01-01
  • 2021-10-05
  • 2015-06-21
  • 1970-01-01
  • 2017-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多