![](/img/trans.png)
[英]How to convert a string array to string type in C++, as in concatenate every element together into one string, and use substring on the string?
[英]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.