now we are all familiar with the function scanf.so lets see..
what do you folks think would this code do?
code1 :::::
[[HIGHLIGHT="C"]
#include<stdio.h>
#include<conio.h>
void main()
{
char c;
clrscr();
printf("Enter a character\n");
scanf("%c",&c);
printf("%c\n",c);
scanf("%c",&c);
printf("%c",c);
getch();
}
[/HIGHLIGHT]
now here in code1 we are entering values for the character c read through scanf.but if we run the program we see that the second scanf is never used by the user.
now lets try some mod.
code 2:::::
[[HIGHLIGHT="C"]
#include<stdio.h>
#include<conio.h>
void main()
{
char c;
clrscr();
printf("Enter a character\n");
scanf("%c",&c);
printf("%c\n",c);
scanf(" %c",&c);
printf("%c",c);
getch();
}
[/HIGHLIGHT]
on running this code2 though we see that all is fine!
So while using scanf for characters we should always take care that no value is left unread from one scanf into the succeeding one.
Like here in code 1 the second scanf reads but a '\n' from the end of the printf above.
but in code 2 we surpass that \n entry by putting a space at the beginning of the control string.
so always try to avoid using scanf and use gets() instead.
scanf woes
Started by Chinmoy, Mar 08 2008 12:39 AM
2 replies to this topic
#1
Posted 08 March 2008 - 12:39 AM
|
|
|
#2
Posted 15 March 2008 - 11:47 AM
Chinmoy said:
so always try to avoid using scanf and use gets() instead.
Some of the most widely circulated bits of entry-level C FAQs for years and years have to be avoid scanf and especially avoid gets! This is typically followed by mention of, "don't void main()" and that <conio.h> and getch are nonstandard C or C++.
#3
Posted 17 March 2008 - 02:33 AM
if that be the case i would prefer getline()!


Sign In
Create Account


Back to top









