RTriplett
RTriplett

Reputation: 23

Making a validation function to tell if the number entered is positve

/* this is just a function I'm trying to make for a bigger program that calcs the area of a room. When the answer <= 0 I want to get the function to take over, but I keep getting to few arguments error when I compile it. Any help will be gladly appreciated.*/

#include <stdio.h>
int validInput(double len);
int main(void)
{
double len ;
int check;
printf("\nEnter length of room in feet:");
        scanf("%lf", &len);
check = validInput();

return 0;

}

int validInput(double len)
{
int check;
if (len <= 0 )
printf("\nNumbers entered must be positive.");
return check;
}

Upvotes: 0

Views: 36

Answers (2)

user3629249
user3629249

Reputation: 16540

this line:

check = validInput();

is missing the parameter. Suggest:

check = validInput( len );

Of course, the code should check the returned value, not the parameter value, from the call to scanf() to assure the operation was successful. In this case, the returned value should be 1. any other returned value would indicate an error occurred.

regarding the validInput() function:

the variable check is never initialized to any specific value. Suggest:

int validInput(double len)
{
    int check = 1; // indicate valid

    if (len <= 0 )
    {
        check = 0; // indicate not valid
        printf("\nNumbers entered must be positive.\n");
    }

    return check;
}

Note: the trailing \n on the call to printf() is to force the text to be output immediately rather than setting in the internal stdout buffer until the program exits, at which time it would be output.

incorporating appropriate error checking into the main() function results in:

#include <stdio.h>   // scanf(), printf()
#include <stdlib.h>  // exit(), EXIT_FAILURE

int validInput(double len);

int main(void)
{
    double len ;
    int check;

    printf("\nEnter length of room in feet:");
    if( 1 != scanf("%lf", &len) )
    { // then scanf failed
        perror( "scanf for length of room, in feet, failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, scanf successful

    check = validInput( len );

    printf( "the user input was %s\n", (check)? "valid" : "not valid");

    return 0;

} // end function: main

Upvotes: 1

mauro
mauro

Reputation: 5950

First... you didn't pass any value to validInput(). I guess your code here above won't even compile...

You should change this line:

check = validInput();

to:

check = validInput(len);

Also consider that variable "check" returned by your function is neither initialised nor set...

P.S. please indent your code...

Upvotes: 1

Related Questions