Detect ENTER in C but as integer type and not Char

2

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");
  scanf("%d",&edad);
  fflush(stdin); 

  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");

  system("pause");
  return 0;
}
    
asked by Morpheo DJman 18.12.2018 в 10:12
source

2 answers

0

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
0

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