Skip to main content

Thread: how does fgets works


i want know how fgets works why fgets able accept space entered in strings not scanf?

here program

code:
#include<stdio.h>  #include<string.h>  int main ()  {  char rt[100];  char temp,*op;  printf("enter string\n");  fgets(rt,11,stdin);  printf("the string entered %s\n",rt);  int i,k,length;  i=0;k=strlen(rt);  printf("strlen gives =%d\n",k);  length=k;  length--;  for(;i<k/2;i++)  {  temp=rt[i];  rt[i]=rt[length-i];  rt[length-i]=temp;  }  printf("the reverse string %s\n",rt);  //printf("expt %s\n\n",rt+6);  op=strrchr(rt,'b');  printf("strrchr gives %c\n",*op);  }
to above program input string

james bond
so able reverse

dnob semaj
but when use scanf(); instead of fgets upto space string stored i.e. james , not word " bond".
scanf not scanning after " " blank character.where fgets not have limitation.
want understand how fgets working i.e. background code or logic running behind fgets() able store space string.

fgets reads line file. manual page fgets:

char *fgets(char *s, int size, file *stream);
...
fgets() reads in @ 1 less size characters stream , stores them buffer pointed s. reading stops after eof or newline. if newline read, stored buffer. '\0' stored after last character in buffer.
the scanf, fscanf functions read sequences of characters according "conversion specifications". "%s" conversion specification (which assume using try match "james bond") defined thus:

matches sequence of non-white-space characters; next pointer must pointer character array long enough hold input sequence , terminating null character ('\0'), added automatically. input string stops @ white space or @ maximum field width, whichever occurs first.
to match "james bond", need conversion specification "%s %s" , result 2 null terminated strings: "james" , "bond".

it's obvious scanf intended breaking predictable lines of input tokens, whereas fgets reading whole lines (including whitespace).


Forum The Ubuntu Forum Community Ubuntu Specialised Support Development & Programming Programming Talk how does fgets works


Ubuntu

Comments

Popular posts from this blog

How to change text Component easybook reloaded *newbee* - Joomla! Forum - community, help and support

PProHeadless.exe has stopped working error when opening projects in Adobe Media Encoder CS6

Preconditions Failed. - Joomla! Forum - community, help and support