hi all,

i jus executed this code on the borland compiler

#include<stdio.h>

void main()
{

char a[20],s[22];

scanf("%s", a);
gets(s);

}


And it only took input from scanf function only

whereas when i tried this code

#include<stdio.h>

void main()
{
char a[20],s[22];

gets(s);
scanf("%s",a);

}


it took input from both the functons.

can anybody tell me why this happened.......

you can also mail me at [email removed]


Thanks......

>can anybody tell me why this happened.......
scanf doesn't work like other input functions. In particular, it treats whitespace differently. The %s modifier will read any number of characters up to whitespace, and a newline is whitespace. gets on the other hand, will read any number of characters up to a newline. I'm sure you see the problem. scanf reads up to a newline, then gets finishes immediately on that newline. The effect is that it seems like gets is skipped when in fact it's working as designed.

Now for the other obligatory stuff:

>void main()
main returns int. Yes, I'm sure. No, your book, compiler, teacher, friend, tutorial, and or conscience are all wrong if they say otherwise.

>scanf("%s", a);
scanf is totally unsafe for reading strings. At the very least you should specify a field width so that extra long strings don't overflow your buffer:

scanf ( "%19s", a );

>gets(s);
gets is identical to scanf's %s without a field width. However, unlike scanf, it's impossible to make gets safe. Please forget that this function even exists and use fgets instead.

you forgot to put an address operator '&'..

code should be like this..

scanf("%s", &a);

>you forgot to put an address operator '&'..
No, an array is already the correct type, so you don't need to use the address-of operator. In fact, by doing so, your code is subtly broken.

you forgot to put an address operator '&'..

code should be like this..

scanf("%s", &a);

a is a char array. It doesn't need the `&'.

[Edit] Not awared of privious post by Narue.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.