Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Input in C. Scanf before gets. Problem

Tags:

c

input

gets

scanf

I'm pretty new to C, and I have a problem with inputing data to the program.

My code:

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

int main(void) {
   int a;
   char b[20];

   printf("Input your ID: ");
   scanf("%d", &a);

   printf("Input your name: ");
   gets(b);   

   printf("---------");

   printf("Name: %s", b);   

   system("pause");
   return 0;
}

It allows to input ID, but it just skips the rest of the input. If I change the order like this:

printf("Input your name: ");
   gets(b);   

   printf("Input your ID: ");
   scanf("%d", &a);

It will work. Although, I CANNOT change order and I need it just as-is. Can someone help me ? Maybe I need to use some other functions. Thanks!

like image 503
Dmitri Avatar asked Mar 02 '10 20:03

Dmitri


People also ask

Why gets is not working after scanf?

Why fgets doesn't work after scanf? This can be solved by introducing a “\n” in scanf() as in scanf(“%d\n”, &x) or by adding getchar() after scanf(). The fgets() function then read this newline character and terminated operation.

Why is gets not taking input in C?

scanf usually leaves a newline in the input stream that will cause problems for fgets. Parse the input for an integer with sscanf and check the return to make sure an integer was input. Show activity on this post. Never use gets() .

What is wrong with scanf in C?

Explanation: The problem with the above code is scanf() reads an integer and leaves a newline character in the buffer. So fgets() only reads newline and the string “test” is ignored by the program.


2 Answers

scanf doesn't consume the newline and is thus a natural enemy of fgets. Don't put them together without a good hack. Both of these options will work:

// Option 1 - eat the newline
scanf("%d", &a);
getchar(); // reads the newline character

// Option 2 - use fgets, then scan what was read
char tmp[50];
fgets(tmp, 50, stdin);
sscanf(tmp, "%d", &a);
// note that you might have read too many characters at this point and
// must interprete them, too
like image 126
AndiDog Avatar answered Oct 06 '22 23:10

AndiDog


scanf will not consume \n so it will be taken by the gets which follows the scanf. flush the input stream after scanf like this.

#include <stdlib.h>
#include <string.h>

int main(void) {
   int a;
   char b[20];

   printf("Input your ID: ");
   scanf("%d", &a);
   fflush(stdin);
   printf("Input your name: ");
   gets(b);   

   printf("---------");

   printf("Name: %s", b);   

   system("pause");
   return 0;
}
like image 32
vinayak Avatar answered Oct 07 '22 01:10

vinayak