如何读取长度未知的输入字符串?

如果我不知道单词有多长,我就不能写 "char m[6];"、 单词的长度可能是十或二十。 如何使用 scanf 从键盘获取输入?

#include <stdio.h>
int main(void)
{
    char  m[6];
    printf("please input a string with length=5\n");
    scanf("%s",&m);
    printf("this is the string: %s\n", m);
    return 0;
}

请输入长度为 5 的字符串 你好 这是字符串:hello

解决办法

在动态保护一个区域的同时进入

例如

#include 
#include 

char *inputString(FILE* fp, size_t size){
//The size is extended by the input with the value of the provisional
    char *str;
    int ch;
    size_t len = 0;
    str = realloc(NULL, sizeof(char)*size);//size is start size
    if(!str)return str;
    while(EOF!=(ch=fgetc(fp)) && ch != '\n'){
        str[len++]=ch;
        if(len==size){
            str = realloc(str, sizeof(char)*(size+=16));
            if(!str)return str;
        }
    }
    str[len++]='\0';

    return realloc(str, sizeof(char)*len);
}

int main(void){
    char *m;

    printf("input string : ");
    m = inputString(stdin, 10);
    printf("%s\n", m);

    free(m);
    return 0;
}
评论(38)

请允许我提出一个更安全的建议:

声明一个足以容纳字符串的缓冲区:

`char user_input[255];``

安全的方式获取用户输入:

fgets(user_input, 255, stdin); `

这是一种安全的获取输入的方法,第一个参数是指向存储输入的缓冲区的指针,第二个参数是函数应读取的最大输入量,第三个参数是指向标准输入的指针,即用户输入的来源。

第二个参数限制了函数的读取量,从而避免了缓冲区超限,因此特别安全。此外,fgets 会对处理后的字符串进行空尾处理。

有关该函数的更多信息 此处

编辑:如果需要进行格式化(例如将字符串转换为数字),可以在获得输入后使用 atoi

评论(2)

如果您对字符串的可能大小有一定的了解,可以使用函数

char *fgets (char *str, int size, FILE* file);`

否则,也可以使用 malloc() 函数在运行时分配内存,该函数可动态提供所需的内存。

评论(0)