簡體   English   中英

如何連接和打印字符串的每個元素?

[英]How to concatenate and print every element of the string?

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

cipher_keyword只分配了 1 個char 你的循環溢出了數組。 所以你的代碼有未定義的行為

您需要循環argv一次以計算所需的總計count ,然后分配數組,然后再次循環argv以填充數組。

填充數組時,需要使用單獨的索引計數器來正確訪問數組元素。 您正在使用內部循環的計數器,它在處理的每個命令行參數上重置為 0。 所以你正在覆蓋數組元素。

您也沒有告訴printf()cipher_keyword有多少char實際可用於打印,無論是通過空終止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;
}

暫無
暫無

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

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