User
User

Reputation: 211

C - How to check if there is a user input

Suppose I initialized integer variable and I'm asking a integer input; e.g. :

int integer;
scanf("%d", &integer);

Question - 1: If the user input nothing, how do i know?

Question - 2: After initializing integer variable (int integer;), what does integer contain?

Upvotes: 0

Views: 6667

Answers (2)

user3629249
user3629249

Reputation: 16540

this is from: https://gcc.gnu.org/ml/gcc-help/2006-03/msg00101.html

/* --- self-identity --- */
#include "kbhit.h"

/* fileno setbuf stdin */
#include <stdio.h>

/* NULL */
#include <stddef.h>

/* termios tcsetattr tcgetattr TCSANOW */
#include <termios.h>

/* ioctl FIONREAD ICANON ECHO */
#include <sys/ioctl.h>

static int initialized = 0;
static struct termios original_tty;


int kbhit() 
{
  if(!initialized)
  {
    kbinit();
  }

  int bytesWaiting;
  ioctl(fileno(stdin), FIONREAD, &bytesWaiting);
  return bytesWaiting;
}

/* Call this just when main() does its initialization. */
/* Note: kbhit will call this if it hasn't been done yet. */
void kbinit()
{
  struct termios tty;
  tcgetattr(fileno(stdin), &original_tty);
  tty = original_tty;

  /* Disable ICANON line buffering, and ECHO. */
  tty.c_lflag &= ~ICANON;
  tty.c_lflag &= ~ECHO;
  tcsetattr(fileno(stdin), TCSANOW, &tty);

  /* Decouple the FILE*'s internal buffer. */
  /* Rely on the OS buffer, probably 8192 bytes. */
  setbuf(stdin, NULL);
  initialized = 1;
}

/* Call this just before main() quits, to restore TTY settings! */
void kbfini()
{
  if(initialized)
  {
    tcsetattr(fileno(stdin), TCSANOW, &original_tty);
    initialized = 0;
  }
}

----------------------------------

To use kbhit:

----------------- demo_kbhit.c -----------------
/* gcc demo_kbhit.c kbhit.c -o demo_kbhit */
#include "kbhit.h"
#include <unistd.h>
#include <stdio.h>

int main()
{
  int c;
  printf("Press 'x' to quit\n");
  fflush(stdin);
  do
  {
    if(kbhit())
    {
      c = fgetc(stdin);
      printf("Bang: %c!\n", c);
      fflush(stdin);
    }
    else usleep(1000); /* Sleep for a millisecond. */
  } while(c != 'x');
}

----------------------------------

IF wanting to use scanf() then check the returned value (not the parameter value.) If the returned value is 1 then the user entered a integer value

Upvotes: 0

Daniel A. White
Daniel A. White

Reputation: 190897

  1. If you don't enter anything, scanf will return a negative value.

    int integer; 
    int result = scanf("%d", &integer);
    if (result > 0) { /* safe to use integer */ }
    
  2. int integer; is initialized to the data which was at the location the program allocated for it. Hence it will look like garbage and should be initialized with a sensible value such as 0.

Upvotes: 3

Related Questions