Rui Yu
Rui Yu

Reputation: 113

Check user input in C with scanf()

Purpose:

If user input b is a float number prints floor(b), round(b), ceil(b).

Else prints scanf error: (%d)\n.

The instruction (provided by our teacher) has a code like this, which I don't understand.

Here's my code: `

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

int main(void) {
    float b;
    printf("Eneter a float number");
    int a=0;
    a=5;
    a=scanf("%d", &b);
    if (a=0)
    {
        printf("scanf error: (%d)\n",a);
    }
    else
    {
        printf("%g %g %g",floor(b), round(b), ceil(b));
    }
    return 0
}

Upvotes: 0

Views: 4909

Answers (2)

VolAnd
VolAnd

Reputation: 6407

Mistake # 1

if (a=0)  // condition will be always FALSE

must be

if (a==0)

or better

if (0 == a)

Mistake # 2

scanf("%d", &b); // when b is float

instead of

scanf("%f", &b);

UPDATE:

Actually, for case of checking results of scanf I personally prefer to use != with number of values entered with the last scanf. E.g. if two comma separated integers required to continue calculation snippet can be:

int x, y;
int check;
do{
    printf("Enter x,y:");
    check = scanf("%d,%d", &x, &y); // enter format is x,y
    while(getchar()!='\n'); // clean the input buffer
}while(check != 2);

that loop will re-ask for input if check is not 2, i.e. if it is 0 (when even the first value is incorrect, e.g. abc,12) or if it is 1 (when user forgot comma or enter not a number after comma, e.g. 12,y

Upvotes: 4

Ed Heal
Ed Heal

Reputation: 60007

Code with corrections and comments - also available here - http://ideone.com/eqzRQe

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

int main(void) {
    float b;
//    printf("Eneter a float number");
    printf("Enter a float number"); // Corrected typo
    fflush(stdout); // Send the buffer to the console so the user can see it
    int a=0;
//    a=5; -- Not required
    a=scanf("%f", &b); // See the manual page for reading floats
    if (a==0) // Need comparison operator not assignemnt
    {
        printf("scanf error: (%d)\n",a); // A better error message could be placed here
    }
    else
    {
        printf("%g\n", b); // Just to check the input with ideone - debugging
        printf("%g %g %g",floor(b), round(b), ceil(b));
    }
    return 0; // You need the semi-colon here
}

For VenuKant Sahu benefit

Return Value

These functions return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.

The value EOF is returned if the end of input is reached before either the first successful conversion or a matching failure occurs. EOF is also returned if a read error occurs, in which case the error indicator for the stream (see ferror(3)) is set, and errno is set indicate the error.

Upvotes: 1

Related Questions