在 C 中动态读取用户输入字符串

lez*_*mon 3 c

给定未知长度的用户输入(由最大长度为 100 的单词组成)。有没有办法逐个字符串动态读取它?

我的理解是 scanf 读取一个字符串直到到达一个空格,所以我尝试使用 scanf 但它进入了一个无限循环。

char buf[101];
while (scanf("%s", buf))
{
    //something is done with the string
}
Run Code Online (Sandbox Code Playgroud)

Che*_*bim 6

给定未知长度的用户输入(由最大长度为 100 的单词组成),有没有办法逐个字符串动态读取它?

构建您自己的功能,而不是scanf有助于实现这一目标

  • 在这里,我创建了一个函数scan,它会通过在每次迭代中增加字符串的大小来动态接收字符串

  • 我使用了额外的头文件string.hstdlib.h原因如下:

    1. 在功能stdlib.h中 (点击了解更多)库文件是动态分配的有用的记忆。

    2. 在功能string.h中 (点击了解更多)库文件都处理字符串有用

注意:用户输入字符串时停止输入end

#include <stdio.h>  //the standard library file
#include <stdlib.h> //library file useful for dynamic allocation of memory
#include <string.h> //library file with functions useful to handle strings

//the function    
char* scan(char *string)
{
    int c; //as getchar() returns `int`
    string = malloc(sizeof(char)); //allocating memory

    string[0]='\0';

    for(int i=0; i<100 && (c=getchar())!='\n' && c != EOF ; i++)
    {
        string = realloc(string, (i+2)*sizeof(char)); //reallocating memory
        string[i] = (char) c; //type casting `int` to `char`
        string[i+1] = '\0'; //inserting null character at the end
    }

    return string;
}

int main(void)
{
    char *buf; //pointer to hold base address of string

    while( strcmp((buf=scan(buf)),"end") ) //this loop will continue till you enter `end`
    {
        //do something with the string

        free(buf); //don't forget to free the buf at the end of each iteration
    }

    free(buf); //freeing `buf` for last input i.e, `end` 

}
Run Code Online (Sandbox Code Playgroud)

让我们//do something with the string看看上面的代码是否有效:)

我在主函数中更改以下 while 循环:

    while( strcmp((buf=scan(buf)),"end") )
    {
        //do something with the string
    }
Run Code Online (Sandbox Code Playgroud)

while( strcmp((buf=scan(buf)),"end") )
{
    printf("you entered : %s\n",buf);
    printf("size        : %u\n",strlen(buf));
    printf("reversing   : %s\n",strrev(buf));

    printf("\n-------------------\n");

    free(buf);
}
Run Code Online (Sandbox Code Playgroud)

现在,

输入 :

hall
of
fame
stay in it
end
Run Code Online (Sandbox Code Playgroud)

输出 :

you entered : hall
size        : 4
reversing   : llah

-------------------
you entered : of
size        : 2
reversing   : fo

-------------------
you entered : fame
size        : 4
reversing   : emaf

-------------------
you entered : stay in it
size        : 10
reversing   : ti ni yats

-------------------
Run Code Online (Sandbox Code Playgroud)