gpt4 book ai didi

c - 使用 scanf 从 stdin 获取任意长度的输入

转载 作者:太空宇宙 更新时间:2023-11-04 01:10:08 25 4
gpt4 key购买 nike

所以我知道的在 C 中进行用户键盘输入的方法之一如下:

char buffer[LENGTH_KNOWN] = "";
scanf("%s",buffer);

我想知道是否有任何方法可以接受任意长度的用户输入。我尝试了如下操作,但最终遇到了段错误。

char* buffer = "";
scanf("%s",buffer);
printf("%s",buffer);

但这似乎有效:

char* buffer = "TEST........keeps going....................."
scanf("%s",buffer);
printf("%s",buffer);

谁能解释为什么我会收到此错误,是否有任何简单的方法可以在不使用 malloc 和检查缓冲区溢出的情况下扫描任意用户输入?

提前致谢!

最佳答案

实际上两者都是错误的,因为您不能写入字符串文字(在您的两个示例中,buffer 都指向字符串文字)。

不可能通过单个scanf 获得任意长度的输入。您需要在循环中获取输入并不断添加到真实缓冲区。

is there any easy way out to scanf arbitrary user input without using malloc and checking buffer overflow

使用现成的函数为您完成。类似于 getline(3)(不幸的是非标准)。

ssize_t getline (char **lineptr, size_t *n, FILE *stream)

This function reads an entire line from stream, storing the text (including the newline and a terminating null character) in a buffer and storing the buffer address in *lineptr.

关于c - 使用 scanf 从 stdin 获取任意长度的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14250896/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com