Detect ENTER in C but as integer type and not Char


I wish that when entering an age number, I would detect if you press ENTER as a whole number to exit the program.

I know that ENTER = '\ n' but it is compared with char variables and what I use is an entire variable.

How would you do? I already tried with scanf, getchar (), fgets (), they all treat ENTER as char, but I can not use it since I will use inequalities with integers when entering the number age

#include <stdio.h>
#include <math.h>
#include <conio.h>

int main()

  int edad;
  printf("INGRESAR TU EDAD (entero mayor que cero) : \n");

  if ( edad<18)
    printf("No puedes votar eres menor de edad\n");
  else if ( edad >=18)
    printf(" Si puedes Votar , eres mayor de edad 18\n");
  else ( edad = '\n')
    printf(" Pulsaste ENTER , saliendo ..\n");

  return 0;
asked by Morpheo DJman 18.12.2018 в 10:12

2 answers


scanf( "%d" ) waits for an integer. What you want is to detect an empty entry , or, maybe, an incorrect conversion .

A possible solution is to check first if the reading of an integer is correct:

if( scanf( "%d",&edad) != 0 ) {
  if( edad < 18)
    printf("No puedes votar eres menor de edad\n" );
  else if ( edad >= 18 )
    printf(" Si puedes Votar , eres mayor de edad 18\n" );

printf( "Saliendo\n" );
answered by 18.12.2018 в 10:24

You have an error on the line:

else ( edad = '\n')

It should be written like this:

else if( edad == '\n')

The scanf function does not return when you enter until you enter some character other than '\ n'.

The '\ n' in number is 10.

answered by 18.12.2018 в 10:25