Jump to content

scanf woes

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
2 replies to this topic

#1
Chinmoy

Chinmoy

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 392 posts
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.

#2
dcs

dcs

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 775 posts

Chinmoy said:

so always try to avoid using scanf and use gets() instead.
"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
Chinmoy

Chinmoy

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 392 posts
if that be the case i would prefer getline()!