简体   繁体   English

fgets内部如何运作?

[英]how does fgets internally works?

Well it is a basic question but I seem confused enough. 嗯,这是一个基本问题,但我似乎很困惑。

#include<stdio.h>
int main()
{
char a[100];
printf("Enter a string\n");
scanf("%s",a);
}

Basically the above is what I want to achieve. 基本上上面就是我想要实现的目标。 If I enter a string 如果我输入一个字符串

James Bond

then I want that to be stored in array a. 然后我想将它存储在数组a中。 But the problem is because of presence of a blank space in between only James word is stored. 但问题是因为只存在James字之间存在空格。 So how can I solve this one. 那么我该如何解决这个问题呢?

UPDATE UPDATE
After the replies given below I understand fgets() would be a better choice. 在下面给出的回复后,我理解fgets()将是更好的选择。 I want to know internal working of fgets as why is it able to store the string with space where as scanf is not able to do the same. 我想知道fgets的内部工作,为什么它能够存储带有空格的字符串,而scanf不能这样做。

Is this what you need? 这是你需要的吗?

All implementations scans the input file(or stream) until it reaches \\n or EOF, or the maxSize param is hit... 所有实现都扫描输入文件(或流),直到达到\\ n或EOF,或者命中maxSize参数...

scanf reads up until the first whitespace character. scanf读取直到第一个空格字符。 The solution is to use fgets, if memory serves me correctly, in your instance it'd be: 解决方案是使用fgets,如果内存正确地为我服务,在你的实例中它将是:

fgets(a, 100, STDIN);

It will read up to 100 characters (or the first \\n) from standard input and store it in a. 它将从标准输入读取最多100个字符(或第一个\\ n)并将其存储在a中。

Do not use the gets function ever, even if it looks easier. 即使它看起来更容易,也不要使用gets函数。

Usually scanf breaks the input at whitespace (space, tab, newline, ...). 通常scanf会在空白处(空格,制表符,换行符......)中断输入。

For example, the input " 5 42 -100" is accepted with scanf("%d%d%d") because each %d strips the leading whitespace. 例如,输入" 5 42 -100"scanf("%d%d%d")接受,因为每个%d剥离前导空格。 The same behaviour happens with %s . %s也会出现相同的行为。

The only conversion specifiers where the ignoring of leading whitespace doesn't happen are %% , %[ and %c (and, for different reasons, %n ) 忽略前导空格的唯一转换说明符是%%%[%c (并且,由于不同的原因, %n

char input[] = " hello world";
char buf[100];
sscanf(input, "%8c", buf); /* buf contains " hello w" */
sscanf(input, "%8[^o]", buf); /* buf contains " hell" */

The fgets function reads as many characters as there are, up to the nest line break. fgets函数读取尽可能多的字符,直到嵌套换行符。


I use The Open Group Base Specifications Issue 7 for online documentation 我使用The Open Group Base Specifications Issue 7进行在线文档

你应该使用gets(a)/ fgets(a,sizeof(a),stdin)而不是sscanf()。

Try fgets() : 试试fgets()

char a[100];
printf("Enter a string\n");
fgets(a, sizeof(a), STDIN);

To learn more about STDIN , check this . 要了解有关STDIN更多信息, 请选中此项

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM