溫馨提示×

c語言怎么輸入未知個數(shù)的字符串

小億
126
2024-05-16 18:04:23
欄目: 編程語言

在C語言中,可以使用動態(tài)內存分配來輸入未知個數(shù)的字符串。具體步驟如下:

  1. 使用malloc函數(shù)動態(tài)分配內存來存儲字符串??梢韵确峙湟粋€較小的初始內存空間,然后在需要輸入更多字符串時再使用realloc函數(shù)來擴展內存空間。
char** strings = malloc(sizeof(char*));
int num_strings = 0;
int max_strings = 1;

char input[100]; // 假設每個字符串最多100個字符

while (1) {
    printf("請輸入字符串:");
    fgets(input, 100, stdin);

    // 去除換行符
    input[strcspn(input, "\n")] = 0;

    // 分配內存來存儲當前輸入的字符串
    strings[num_strings] = malloc(strlen(input) + 1);
    strcpy(strings[num_strings], input);

    num_strings++;

    // 如果需要更多內存空間,則擴展內存
    if (num_strings == max_strings) {
        max_strings *= 2;
        strings = realloc(strings, max_strings * sizeof(char*));
    }

    // 判斷是否繼續(xù)輸入
    printf("是否繼續(xù)輸入?(y/n): ");
    char choice;
    scanf(" %c", &choice);
    if (choice != 'y') {
        break;
    }
}
  1. 在結束輸入后,記得釋放分配的內存空間。
// 輸出所有輸入的字符串
for (int i = 0; i < num_strings; i++) {
    printf("字符串%d: %s\n", i+1, strings[i]);
}

// 釋放內存
for (int i = 0; i < num_strings; i++) {
    free(strings[i]);
}
free(strings);

通過以上方法,可以輸入未知個數(shù)的字符串,并使用動態(tài)內存分配來存儲這些字符串。

0