Dev-C++ Input skipped

Ravitheja picture Ravitheja · Aug 10, 2012 · Viewed 7.4k times · Source
#include<stdio.h>
#include<conio.h>
main()
{
      int i;
      char c, text[30];
      float f;
      printf("\nEnter Integer : ");
      scanf("%d",&i);
      printf("\nEnter Character : ");
      c = getch();
      printf("\nEnter String:");
      gets(text);
      printf("\nEnter Float:");
      scanf("%f",&f);
      printf("\nInteger : %d",i);
      printf("\nCharacter : %c8",c);
      printf("\nString : %s",text);
      printf("\nFloat : %f",f);
      getch();
}

Why is this simple program not able to read a string using the gets() function? What else should I use to correct it? Well it it worked in Turbo C in my old 32-bit PC but not here...

Answer

Muhammad Farag picture Muhammad Farag · Aug 10, 2012

With some little research, I guess that the problem comes with scanf(). scanf() reads a line without the end of line character '\n' which seems to stay in the buffer and actually red by the next statement.

alternatively you can use fgets() and sscanf() as follows:

To read a character I used:

fgets(text,sizeof(text),stdin);
sscanf(text,"%c",&c); /* or: c = text[0]; */

to read an integer I have used

fgets(text,sizeof(text),stdin);
sscanf(text,"%d",&i);

I had a major problem with gets() in a C course I had (to which DevC++) was advised as a compiler. However, I totally recall I didn't follow the advice and it turned out that the behavior of fgets() is also compiler dependent.

The man page for gets() has this:

BUGS

Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead.