This code was originally for an assignment. I met the requirements of the assignment but wish to expand the code to further check for valid input. I am quite new at this but trying to learn...

Anyway, the problem is this. I can check if the float is non-negative with a simple loop as such:

int main(void)
{
    //initialize variable
    float fDollars=0.00;
    
    //prompt for and accept input
    printf("Please enter a dollar amount: ");
    scanf("%f", &fDollars);
    
    //check user response as valid
    while (fDollars <= 0.00)
    {
                printf("\nYou entered an invalid response.");
                printf("\nPlease enter a postive amount: ");
                scanf("%f", &fDollars);
    } //end while

    return 0;
} //end main

I can alternatively check to see if the input is not a character with the following:

//Loop until user inputs a valid dollar amount
      while (scanf("%f", &fDollars) != 1)
      {
         while (getchar() != '\n');
         printf ("Please enter a dollar amount: ");
      } //End loop

      printf ("You entered %.2f\n", fDollars);

However, I am not able to check both with any success.

I have read that scanf is not preferred but I am not sure what else to use.

Also, would it be better to accept the float as a string and then convert to a float? I think it would be for validation but do not even know where to begin on that one.

If anyone is interested in looking at the entire program, it is attached. I know I still have some other things to work on with it to make it more robust and user-proof. However, I am using this to learn.

Thanks.

Attachments
/*
  Name: Currency Conversion Program
  Author: Micah Stanley
  Date: 23/09/09 11:12
  Description: Simple program to convert USD to five different types of currency.
*/

//Include the header files
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>

//Define the currency exchange rates that will be used
#define JapaneseYen 92.5668
#define EuropeanEuro 0.703235
#define BritishPound 0.615401
#define KuwaitiDinar 0.2876
#define MexicanPeso 13.64

//Prototype the Functions
void displayMenu(void);
char menuChoice(char *);
float convertCurrency(char, float);
float validateDollars(float);
float validatePositive(float);

//Begin the Main Function
int main(void)
{
    
    //Define, Initialize, and Assign variables
    char cReturnedMenuChoice;
    float fUSDollars=0.00;
    float fConvertedAmount=0.00;
    
    //Display title and date of exchange rate
    printf("\n\t   Currency Conversion Program,  by Micah Stanley\n");
    printf("\n\t\tExchange rate as of 3 September 2009\n");
    
    //Display the menu options
    displayMenu();
    
    //Allow user input
    menuChoice(&cReturnedMenuChoice);
    
    //Call the convert currency function
    convertCurrency(cReturnedMenuChoice, fUSDollars);
    
 return 0;
} //End Main Function
    
//Display menu function
void displayMenu()
{
     //Display the menu options
  	 printf("\n\nPlease select a currency.");
	 printf("\n\n[A]   Japanese Yen\n");
	 printf("[B]   European Euro\n");
	 printf("[C]   British Pound\n");
	 printf("[D]   Kuwaiti Dinar\n");
	 printf("[E]   Mexican Peso\n");
	 printf("[Q]   Quit\n");
	 printf("\nEnter your selection:");
}//End displayMenu function

char menuChoice(char *SELECTION)
{
     char cMenuChoice;
     char cUpperMenuChoice;

     scanf("%c", &cMenuChoice);
     
     //Convert user input to uppercase
    cUpperMenuChoice=toupper(cMenuChoice);
    
    *SELECTION = cUpperMenuChoice;
}

float convertCurrency(char cReturnedMenuChoice, float fUSDollars)
{
     //Define local variables
     float fConvertedAmount=0.00;

     printf("\nThe received variable is: %c", cReturnedMenuChoice);
         //Develop Case to return the correct response
    switch(cReturnedMenuChoice)
    {
         case 'A':
              printf("\nThe exchange rate for the Japanese Yen is: %.4f\n", JapaneseYen);
              printf("\nPlease enter the dollar amount (in US Dollars) to be converted: $ ");
              scanf("%f", &fUSDollars);
              
     
              //Check for positive amount
              fUSDollars=validateDollars(fUSDollars);
                   
              // Perform Conversion
              fConvertedAmount=(JapaneseYen * fUSDollars);
              printf("\n$%.2f USD converts to %.2f Japanese Yen.", fUSDollars, fConvertedAmount);
              printf("\n");
              break; //End case 'A'
              
         case 'B':
              printf("\nThe exchange rate for the European Euro is: %.6f\n", EuropeanEuro);
              printf("\nPlease enter the dollar amount (in US Dollars) to be converted: $ ");
              scanf("%f", &fUSDollars);
              
              //Check for positive amount
              fUSDollars=validateDollars(fUSDollars);
                   
              // Perform Conversion
              fConvertedAmount=(EuropeanEuro * fUSDollars);
              printf("\n$%.2f USD converts to %.2f European Euros.", fUSDollars, fConvertedAmount);
              printf("\n");
              break; //End case 'B'
              
         case 'C':
              printf("\nThe exchange rate for the British Pound is: %.6f\n", BritishPound);
              printf("\nPlease enter the dollar amount (in US Dollars) to be converted: $ ");
              scanf("%f", &fUSDollars);
               
              //Check for positive amount
              fUSDollars=validateDollars(fUSDollars);
                  
              //Perform conversion
              fConvertedAmount=(BritishPound * fUSDollars);
              printf("\n$%.2f USD converts to %.2f British Pounds.", fUSDollars, fConvertedAmount);
              printf("\n");
              break;
              
         case 'D':
              printf("\nThe exchange rate for the Kuwaiti Dinar is: %.4f\n", KuwaitiDinar);
              printf("\nPlease enter the dollar amount (in US Dollars) to be converted: $ ");
              scanf("%f", &fUSDollars);
                  
              //Check for numeric entry
              fUSDollars=validateDollars(fUSDollars);
                   
              //Perform conversion
              fConvertedAmount=(KuwaitiDinar * fUSDollars);
              printf("\n$%.2f USD converts to %.2f Kuwaiti Dinar.", fUSDollars, fConvertedAmount);
              printf("\n");
              break;
              
         case 'E':
              printf("\nThe exchange rate for the Mexican Peso is: %.2f\n", MexicanPeso);
              printf("\nPlease enter the dollar amount (in US Dollars) to be converted: $ ");
              scanf("%f", &fUSDollars);
                   
              //Check for positive amount
              fUSDollars=validateDollars(fUSDollars);
                  
              //Perform conversion
              fConvertedAmount=(MexicanPeso * fUSDollars);
              printf("\n$%.2f USD converts to %.2f Mexican Pesos.", fUSDollars, fConvertedAmount);
              printf("\n");
              break;
         case 'Q':
              printf("\nThank you, Have a nice day!");
              printf("\n");
              return 0;
                 
         default:
              printf("\nYou entered an invalid response. ");
              printf("Program will now exit.");
              printf("\n");
              break;
    } //End case
    
} //End convertCurrency

float validateDollars(float fUSDollars)
{ 
      
    while (fUSDollars <= 0.00)
              {
                    printf("\nYou have entered a negative amount.\n");
                    printf("\nPlease enter a positive dollar amount: $ ");
                    scanf("%f", &fUSDollars);
              } //End while loop
              
     return fUSDollars; //Return the validated input
} //End validateDollars function

float validatePositive(float fUSDollars)
{
      while (scanf("%f", &fUSDollars) <= 0.00)
      {
           if (fUSDollars <=0.00)
           {
                printf("\nPlease enter a positive dollar amount: ");
                scanf("%f", &fUSDollars);
           } //end if
           else
           {
               //Loop until user inputs a valid dollar amount
               while (scanf("%f", &fUSDollars) != 1)
               {
                     while (getchar() != '\n');
                     printf ("Please enter a dollar amount: ");
               } //End inner while loop
           } //end else
      } //end while
} //end validatePositive function

Try combining the tests like this:

int code;

while ((code = scanf("%f", &fDollars)) != 1 || fDollars <= 0)
{
    printf("invalid amount. please enter a positive amount: ");
    fflush(stdout);

    if (code != 1) FLUSH_STDIN();
}

Further reading for extra credit can be found here.

Edited 7 Years Ago by Tom Gunn: n/a

Try combining the tests like this:

int code;

while ((code = scanf("%f", &fDollars)) != 1 || fDollars <= 0)
{
    printf("invalid amount. please enter a positive amount: ");
    fflush(stdout);

    if (code != 1) FLUSH_STDIN();
}

Further reading for extra credit can be found here.

Thanks, I had been thinking along those lines previously--trying to combine them. However, when combined, the program will accept an input and go to a new line on carriage return but will not continue the loop until a character is entered.

Your code is similar to what I tried and I get the same result. How could I input as a string and then compare and convert to a double? I think that atof would serve that purpose but I am not sure of the proper syntax.

scanf() does not treat new line characters as different from other white space. To get line oriented input you should use something like fgets(). sscanf() is an easy way to parse the line fgets() reads:

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

int main()
{
    char line[BUFSIZ];
    float dollars;

    while (fgets(line, sizeof line, stdin) &&
           sscanf(line, "%f", &dollars) != 1 ||
           dollars <= 0)
    {
        printf("invalid amount. please enter a positive amount: ");
        fflush(stdout);
    }

    printf("Received %f\n", dollars);

    return 0;
}

Edited 7 Years Ago by Tom Gunn: n/a

Works like a charm! I will have to dissect all of that and figure out why it works like this. Thanks for helping me figure this out.

This question has already been answered. Start a new discussion instead.