Home > other >  How to add incorrect input to this code, can't use 'switch'
How to add incorrect input to this code, can't use 'switch'

Time:11-02

I have this code, and idk how to add Incorrect input, If i write letters instead of numbers

#include <stdio.h>
int main()
{
    float k;
    printf("Give a number: ");
    scanf("%f", &k);
    if (k > 0)
        printf("positive", k);
    if (k < 0)
        printf("negative", k);
    if (k == 0)
        printf("null",k);
    return 0;
}

CodePudding user response:

Function scanf returns a number of successfully scanned arguments. Therefore you can add a check if scanf returns 1.

if (scanf("%f", &k) != 1) {
  printf("Invalid input")
} else if (k>0) {
  printf("positive");
} else if (k<0) {
  printf("negative");
} else if (k == 0) {
  printf("zero");
} else { // yes yes ... it can happen
  printf("not-a-number");
}
  •  Tags:  
  • c
  • Related