What is the difference between scanf and gets?

Problem : NOPC1

My code using scanf : scanf

My code using gets : gets

Apart from the input method everything else is same in the codes. Then why the outputs of both are different?

gets reads an entire line from standard input. But scanf only reads what you tell it to.

In your case, you told scanf to read just a single %s, which means just a bunch of non-whitespace characters. So, it quits reading from input, when it encounters the first white-space character.

To know the difference, try printing your a and b, immediately after reading them, and look at what is getting printed.


And one more thing, while using scanf:

Suppose your character array is char a[SIZE];. Then, the correct way to read an input into a from stdin is scanf("%s", a); and not as scanf("%s", &a); (Notice that you do not require an ampersand (&) while reading strings.)

1 Like

Oh, and one more thing: You can read more about scanf and its various format specifiers available here.

And for your purpose, the code given below contains your program, modified to read an entire line using scanf

#include <stdio.h>
#include <string.h>

int main() 
	char a[50], b[40];
	scanf ("%[^\r\n]", a);
	scanf ("%s", b);
	if (strstr(a, b) != NULL)
		printf ("Y\n");
		printf ("N\n");	
	return 0;

%[...] is almost same as %s. But, %[...] accepts only the characters specified within the box, and quits, when it encounters the first character not in the box.

%[^...] is the exact reverse of %[...] and accepts any character not specified after the ^ in the box. It quits reading, when it encounters the first character specified after the ^ in the box. (This explains why [^\n] will read input till end-of-line!!)

1 Like

You can always edit your own post, do not need to add 4 answers… Especially when order of your posts is not guaranteed (if, I not wrong default ordering is by votes and not time…)

I usually type it in my editor (Sublime Text 2 - I am in love with it) and paste it here. That is why, this answers!! Converting to comments!! :smiley:

Maybe it’s safer to use [^\r\n], because AFAIK it’s not garanteed, that lines end with \n character…

1 Like

Yes!! Edited!!

You can write it in whatever you want, my advice is just to click on edit button and add those new ideas to your post :wink:

1 Like

@tijoforyou scanf ("%[^\r\n]", a); What’s the use of \r in this statement?

windows lines ends with \r\n instead of \n as on linux

in editor (mcedit) you can see ^M at the end of such lines…


And I think, lines end with just \r in Mac. So, as @betlista said, it is safer to use \r\n instead of just \n or just \r.

gets is a bug is must be used very care fully. you can over run buffer, causing buffer over flow and program behaves unevenly . where it can be avoided using scanf.