Thread: how does fgets works
i want know how fgets works why fgets able accept space entered in strings not scanf?
here program
to above program input stringcode:#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); }
so able reversejames bond
but when use scanf(); instead of fgets upto space string stored i.e. james , not word " bond".dnob semaj
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:
the scanf, fscanf functions read sequences of characters according "conversion specifications". "%s" conversion specification (which assume using try match "james bond") defined thus: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.
to match "james bond", need conversion specification "%s %s" , result 2 null terminated strings: "james" , "bond".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.
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
Post a Comment