使用 fgets() 将字符放入数组会创建自动输入吗?
Using fgets() to put a character into an array creates automatic input?
我想接收用户输入的单个字符,然后使用 printf() 和 fgets() 方法将其打印出来(这是一个更大程序的一部分,但是这个是孤立的问题)。
include <stdio.h>
include <stdlib.h>
char input[1];
int main(){
printf("Please enter the minimum value the random number can be: ");
fgets(input, sizeof(input), stdin);
printf("\n%c", input[0]);
}
我希望上面的代码如何工作
我认为它会打印出 printf() 消息,然后等待用户输入。无论他们输入什么,我都希望它能获取该输入的第一个字符,然后再向下一行打印出来。
上面的代码是如何工作的
程序打印初始的 printf() 语句,然后在下面打印出一个空行,然后程序终止。
这到底是为什么??为什么代码以那种方式响应而不是我期望的方式?
您需要 space 来存储 NUL 终止符,因此提供大小为 1 的缓冲区意味着无法输入数据。
很可能 fgets
正在检测到这一点并正在退出。将数组大小更改为 2
会导致它等待输入。
来自 C11
,第 7.21.7.2 章,fgets()
概要和描述,(强调我的)
char *fgets(char * restrict s, int n, FILE * restrict stream);
The fgets
function reads at most one less than the number of characters specified by n
from the stream pointed to by stream into the array pointed to by s
. [...]
关于少一个的原因,
[...] A
null character is written immediately after the last character read into the array.
在你的例子中,提供的 n
的值是 1
,因此 fgets()
实际上没有读取任何东西!
解决方案:您需要将数组大小更改为两个 2,一个元素用于输入,一个元素用于终止 null。
我想接收用户输入的单个字符,然后使用 printf() 和 fgets() 方法将其打印出来(这是一个更大程序的一部分,但是这个是孤立的问题)。
include <stdio.h>
include <stdlib.h>
char input[1];
int main(){
printf("Please enter the minimum value the random number can be: ");
fgets(input, sizeof(input), stdin);
printf("\n%c", input[0]);
}
我希望上面的代码如何工作
我认为它会打印出 printf() 消息,然后等待用户输入。无论他们输入什么,我都希望它能获取该输入的第一个字符,然后再向下一行打印出来。
上面的代码是如何工作的
程序打印初始的 printf() 语句,然后在下面打印出一个空行,然后程序终止。
这到底是为什么??为什么代码以那种方式响应而不是我期望的方式?
您需要 space 来存储 NUL 终止符,因此提供大小为 1 的缓冲区意味着无法输入数据。
很可能 fgets
正在检测到这一点并正在退出。将数组大小更改为 2
会导致它等待输入。
来自 C11
,第 7.21.7.2 章,fgets()
概要和描述,(强调我的)
char *fgets(char * restrict s, int n, FILE * restrict stream);
The
fgets
function reads at most one less than the number of characters specified byn
from the stream pointed to by stream into the array pointed to bys
. [...]
关于少一个的原因,
[...] A null character is written immediately after the last character read into the array.
在你的例子中,提供的 n
的值是 1
,因此 fgets()
实际上没有读取任何东西!
解决方案:您需要将数组大小更改为两个 2,一个元素用于输入,一个元素用于终止 null。