nicotineinfused
nicotineinfused

Reputation: 85

How do I display a message or respond towards an invalid input in C

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

int main()
{
    int a, result;
    float b;
    printf("**This is a simple arithmetic calculator.** \n");
    printf("\n Please enter an integer: ");
    scanf("%i ", a);
    printf("Please enter a floating point number: ");
    scanf("%f", b);

    result = a + b

    printf("Output: ");
    printf("%i + %f = %lf \n", a, b, result);
    printf("%i - %f = %lf \n", a, b, result);
    printf("%i * %f = %lf \n", a, b, result);
}

I need to ensure that your program will not crash if the user enters an invalid input.

Upvotes: 1

Views: 546

Answers (2)

moongom
moongom

Reputation: 29

use while loop or if for scanf

while(scanf("%i ", a) !=1){
    printf("invalid input.\n");
}

and

while(scanf("%f", b) !=1){
    printf("invalid input.\n");
}

Upvotes: 0

CodeMonkey
CodeMonkey

Reputation: 12434

scanf is a function that has also got a return value which indicates how many inputs were inserted correctly. So you can just do something like:

while (scanf("%i ", a) != 1)
{
   printf("wrong input, try again");
}

Upvotes: 3

Related Questions