-1

I want the program to ask the user for a number, and if the user does not enter a number the program will say "input not a integer."

Thx for the help guys!

  • You might want to check what e.g. [`scanf`](http://en.cppreference.com/w/c/io/fscanf) returns. Or about the [`strtol`](http://en.cppreference.com/w/c/string/byte/strtol) function. – Some programmer dude Dec 04 '16 at 18:28
  • 5
    Possible duplicate of [Validate scanf parameters](http://stackoverflow.com/questions/23497475/validate-scanf-parameters) – Eli Sadoff Dec 04 '16 at 18:29
  • 1
    Read the line of user input with `fgets()`. If the resultant string successfully parses to an `int`, then it is good, else "input not a integer.". (Avoid `scanf()`) – chux - Reinstate Monica Dec 04 '16 at 18:31

2 Answers2

1

I propose this (it doesn't handle integer overflow):

#include <stdio.h>

int main(void)
{

    char buffer[20] = {0};    // 20 is arbitrary;
    int n; char c;

    while (fgets(buffer, sizeof buffer, stdin) != NULL) 
    {
        if (sscanf(buffer, "%d %c", &n, &c) == 1)
            break;

        else
            printf("Input not integer. Retry: ");
    }

    printf("Integer chosen: %d\n", n);

    return 0;
}

EDIT: Agreed with chux suggestions below!

yLaguardia
  • 585
  • 3
  • 7
  • 1
    Minor: 1) Could simplify to `"%d %c"` (first space not needed as %d consumes leading spaces.) 2) Better to `while (fgets(buffer, sizeof buffer, stdin) != NULL) {;` – chux - Reinstate Monica Dec 04 '16 at 21:39
0

One possible way: use scanf() function to read the input. It returns the number of items it successfully read.

Another way: read the input as string with scanf() of fgets() and then try to parse it as integer.

Community
  • 1
  • 1
Andrey Moiseev
  • 3,914
  • 7
  • 48
  • 64