Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scanf() function doesn't work? [duplicate]

Tags:

c

This may be a simple question, but i searched a lot and still didn't figure it out. I compiles below snip code by gcc and run program from terminal. In correct, It allow to enter an int and a char but it doesn't. It doesn't wait to enter the char??

Anyone here can help me will be kind. thanks in advance!

#include <stdio.h>

int main()
{

  char c;
  int i;

  // a
  printf("i: ");
  fflush(stdin); scanf("%d", &i);

  // b
  printf("c: ");
  fflush(stdin); scanf("%c", &c);

  return 0;

}

like image 805
dangnam2910 Avatar asked Dec 12 '22 12:12

dangnam2910


2 Answers

%d will read consecutive digits until it encounters a non-digit. %c reads one character. Probably what's happening is that you're giving it a number (several digits) followed by a new line. %c then reads in that new line. You were probably intending for the fflush(stdin); to discard anything that hadn't yet been read, but unfortunately, that's undefined behavior.

The solution is to discard all whitespace before reading the character:

scanf(" %c", &c);

Note the space at the start. That means to discard all whitespace.

like image 106
icktoofay Avatar answered Dec 26 '22 21:12

icktoofay


You can use the getchar() to achieve what you want.

or consume the extra newline by using:-

 scanf(" %c", &c);
  ^^^   <------------Note the space

Reason:- Your next scanf for reading the character just reads/consumes the newline and hence never waits for user input

like image 41
Rahul Tripathi Avatar answered Dec 26 '22 21:12

Rahul Tripathi