How to input a string of unknown length in the C language?

In C language, you can use the dynamic memory allocation functions malloc() and realloc() to input strings of unknown length. Initially, you can use malloc() to allocate memory for storing the string, and then use realloc() to adjust the memory size as needed.

Here is an example code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    char *input = (char *)malloc(100); // 初始分配100个字节的内存空间
    char *temp;
    int len = 0;
    
    if (input == NULL) {
        printf("内存分配失败\n");
        return 1;
    }
    
    printf("请输入字符串:\n");

    while(1) {
        if (len >= 100) {
            // 调整内存空间大小
            temp = (char *)realloc(input, len + 10);
            if (temp == NULL) {
                printf("内存分配失败\n");
                free(input);
                return 1;
            } else {
                input = temp;
            }
        }

        // 逐字符读取输入
        input[len] = getchar();
        
        if (input[len] == '\n') {
            input[len] = '\0';
            break;
        }
        
        len++;
    }

    printf("输入的字符串为:%s\n", input);

    free(input);
    
    return 0;
}

In this sample code, a memory space of initial size of 100 bytes is allocated using the malloc() function to store a string. Then, within a loop, the input string is read character by character and the size of the memory space is adjusted as needed using the realloc() function. Once the input is finished, the inputted string is printed and the memory space is released.

bannerAds