0

I need to check that if the user input a value, the program runs only if the value is a positive integer between [1-8] (Inclusive), but if the input value is a letter or word or not input at all (Enter), the program ask again for an input

#include <stdio.h>


int main (){

int height;

do {
    printf  ("Height: ");
    scanf ("%i", &height);
}

while (height < 1 || height > 8);   

{ .
  .
  .
  .

I was thinking to add another condition "|| (or)" in the while validation, something like while "height be different(!=) from an integer" then do...

But I can't figure out how to check that statement in other StackOverflow questions. I hope you can enlighten me

2 Answers2

1

use fgets()

char buf[1000];
if (!fgets(buf, sizeof buf, stdin)) {
    exit(EXIT_FAILURE);
}
if (buf[1] != '\n') exit(EXIT_FAILURE);
if (*buf < '1') exit(EXIT_FAILURE);
if (*buf > '8') exit(EXIT_FAILURE);
// use *buf, maybe (*buf - '0')

an input of "<ENTER>", "0<ENTER>", "12<ENTER>", "a<ENTER>", "<SPACE>3<ENTER>", ... will exit with failure

pmg
  • 106,608
  • 13
  • 126
  • 198
  • thanks @pmg, but I don't want to exit the program, instead I want to ask the users again and again until they type a correct value, something like that: "Inster a value betwen 1 - 8" Height: -1 Height: 0 Height: 42 Height: 50 Height: 4 Height: Correct!! – Juan Pablo Yepes Dec 17 '19 at 16:06
  • @JuanPabloYepes, well, put the code inside an infinite loop and replace the `exit` with `continue`. Add whatever prompt you like and a `break` when the input is correct. – pmg Dec 18 '19 at 07:43
0

I've found this answered question: Check if input is integer type in C

This question only will solve the part about being able to know is the input of the scanf is a number or not, which seems on of the main points. You will still have to check if the input is positive or if it's in the range you want.

jgalaso
  • 22
  • 4
  • Please flag as duplicate, instead of linking to another answer; or elaborate what the relevant difference is. – Yunnosch Dec 17 '19 at 15:45