开发者

how does fgets internally works?

Well it is a basic question but I seem confused enough.

#include<stdio.h&开发者_开发知识库gt;
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. But the problem is because of presence of a blank space in between only James word is stored. So how can I solve this one.

UPDATE

After the replies given below I understand fgets() would be a better choice. 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.


Is this what you need?

  • freeBSD: http://www.freebsd.org/cgi/cvsweb.cgi/src/lib/libc/stdio/fgets.c?rev=1.14.14.1;content-type=text%2Fplain
  • open implementation: https://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=7425&lngWId=3
  • OWP(dead) http://www.koders.com/c/fid042417FA231704B84308A66E1B82EADEDAB22051.aspx
  • ReactOS http://www.koders.com/c/fidEB3507945463053CEFCD518EA0CDFF9EB78E24C9.aspx?s=fgets.c#L1

All implementations scans the input file(or stream) until it reaches \n or EOF, or the maxSize param is hit...


scanf reads up until the first whitespace character. The solution is to use fgets, if memory serves me correctly, in your instance it'd be:

fgets(a, 100, STDIN);

It will read up to 100 characters (or the first \n) from standard input and store it in a.

Do not use the gets function ever, even if it looks easier.


Usually scanf breaks the input at whitespace (space, tab, newline, ...).

For example, the input " 5 42 -100" is accepted with scanf("%d%d%d") because each %d strips the leading whitespace. The same behaviour happens with %s.

The only conversion specifiers where the ignoring of leading whitespace doesn't happen are %%, %[ and %c (and, for different reasons, %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.


I use The Open Group Base Specifications Issue 7 for online documentation


You should use gets(a)/fgets(a, sizeof(a), stdin) instead of sscanf().


Try fgets():

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

To learn more about STDIN, check this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜