Link to home
Start Free TrialLog in
Avatar of JCochran1977
JCochran1977Flag for United States of America

asked on

C Programming - error checking

Any advice or help adding an error check to this program so it displays an error if a user enters a letter instead of number? I am lost:-(

/*********************************************************
Currency Conversion Program
Assignment Description: Accept one input currency,
then display in US Dollars
Name: Student

Course Information: Programming Concepts-CSS-561
      Course Details: Introduction to Programming
      
Assignment No:  Week Five Assignment

Created:
    Started:  7/18/2007
    End Date: 7/22/2007
   
Modifications:
Ver1:  Originally i had the week six and five assignments confused
Ver2:  Skimmed this program down to meet the requirements
Ver3:  Kept the ending statements thanking user for using my program
************************************************************/

#include <stdio.h>
#include <ctype.h>
int main (void)
{

/* Below are the abbreviations used for program */

/* Used the following website to find the conversion */
/* http://www.x-rates.com/calculator.html */

float CNY; /* Variable for Chinese Yuan */

   printf("Currency Conversion\n"); /* Title of Program */
   printf("-------------------\n"); /* line of dashes for separation */  
   printf("\n"); /* insert a blank line */
   printf("Week Five Assignment CSS-561\n"); /* Assignment Week */
   printf("Jessie Cochran\n");  /* My Name */
   printf("\n"); /* insert a blank line */
   printf("Please input an amount to convert\n");
   printf("in Chinese Yuan\n"); /* Asking user to choose from a list of choices */
   printf("\n"); /* insert a blank line */

   printf("\n"); /* insert a blank line */

           
            printf("Enter the value for Chinese Yuan Conversion:");
            scanf("%f",&CNY);
           
            printf("\n");/* insert a blank line */
            printf("\nThe US Dollar Equivalent is ");
            printf("%f", CNY/7.5948); /* Math calculation */
           

   printf("\n");
         
         {
         printf("This is the end of my program");
         printf("\n");/* insert a blank line */
         printf("\n");/* insert a blank line */
         printf("I Hope you enjoyed using my conversion calculator");
         printf("\n");/* insert a blank line */
         printf("\n");/* insert a blank line */
         printf("Please hit Enter to close the program");
         }      

      getchar (); /* Add this line to stop the screen from closing immediately. */
      return 0;

}
Avatar of Infinity08
Infinity08
Flag of Belgium image

get the return value of scanf. It returns the number of correctly read values. So, if the user enters a letter, it will return 0 - if the user enters a correct float, it will return 1 :

            if (1 != scanf("%f",&CNY)) {
                printf("You entered an invalid float value !");
                return 1;
            }

Instead of ending the program, you could also let the user try again, by adding a loop, but I'll leave that up to you.
Here's a reference page for scanf :

        http://www.cplusplus.com/reference/clibrary/cstdio/scanf.html

Check the paragraph on the return value for more information ...
Even though that will work, I usually recommend to read everything as a string and convert it accordingly, e.g.

int get_valid_float_value(conat char* buf, floar* result) {

char* pcCnvEnd;
float val;

val = (float)strtod(buf,&pcCnvEnd);

if (*pcCnvEnd != '\0') { // some alphanumeric value was entered

  return -1;
}

*result = val;

return 0; // everything OK
}

       do {

            char buf[255];
            printf("Enter the value for Chinese Yuan Conversion:");
            scanf("%s",buf);

            } while(0 != get_valid_float_value(buf,&CNY));

           
            printf("\n");/* insert a blank line */
            printf("\nThe US Dollar Equivalent is ");
            printf("%f", CNY/7.5948); /* Math calculation */
Avatar of JCochran1977

ASKER

Should this go at the top of the program or in the middle? I am a very new to programming. I apologize for the silly questions?
If you are referring to

int get_valid_float_value(const char* buf, floar* result) {

char* pcCnvEnd;
float val;

val = (float)strtod(buf,&pcCnvEnd);

if (*pcCnvEnd != '\0') { // some alphanumeric value was entered

  return -1;
}

*result = val;

return 0; // everything OK
}

Since that is a function, you can place it anywhere outside 'main()', given that you provide a prototype:

#include <stdio.h>
#include <ctype.h>

int get_valid_float_value(const char* buf, floar* result); // prototype

int main (void)
{
//...
}

int get_valid_float_value(const char* buf, floar* result) {
//...
}
>> Should this go at the top of the program or in the middle? I am a very new to programming. I apologize for the silly questions?

Mine is the easiest change, and probably fits your experience level best (have you already learned about functions ?).

Just replace the scanf you had in your code with the block of code I posted.
Infinity08: The program compiles without problems and runs, but if i put in a letter the command window disappears, if i enter a number it works? Any ideas?

/*********************************************************
Currency Conversion Program
Assignment Description: Accept one input currency,
then display in US Dollars
Name: Jessie Cochran

Course Information: Programming Concepts-CSS-561
      Course Details: Introduction to Programming
     
Assignment No:  Week Five Assignment

Created:
    Started:  7/18/2007
    End Date: 7/28/2007
   
Modifications:
Ver1:  Originally i had the week six and five assignments confused
Ver2:  Skimmed this program down to meet the requirements
Ver3:  Kept the ending statements thanking user for using my program
Ver4:  Realized I didn't meet the requirements. worked in the error checking
************************************************************/

#include <stdio.h>
#include <ctype.h>
int main (void)
{

/* Below are the abbreviations used for program */

/* Used the following website to find the conversion */
/* http://www.x-rates.com/calculator.html */

float CNY; /* Variable for Chinese Yuan */

   printf("Currency Conversion\n"); /* Title of Program */
   printf("-------------------\n"); /* line of dashes for separation */  
   printf("\n"); /* insert a blank line */
   printf("Week Five Assignment CSS-561\n"); /* Assignment Week */
   printf("Jessie Cochran\n");  /* My Name */
   printf("\n"); /* insert a blank line */
   printf("Please input an amount to convert\n");
   printf("in Chinese Yuan\n"); /* Asking user to choose from a list of choices */
   printf("\n"); /* insert a blank line */

   printf("\n"); /* insert a blank line */

           
            printf("Enter the value for Chinese Yuan Conversion:");
           
            if (1 != scanf("%f",&CNY)) {
                printf("You entered an invalid float value !");
                return 1;
            }
           
            printf("\n");/* insert a blank line */
            printf("\nThe US Dollar Equivalent is ");
            printf("%f", CNY/7.5948); /* Math calculation */
           

   printf("\n");
         
         {
         printf("This is the end of my program");
         printf("\n");/* insert a blank line */
         printf("\n");/* insert a blank line */
         printf("I Hope you enjoyed using my conversion calculator");
         printf("\n");/* insert a blank line */
         printf("\n");/* insert a blank line */
         printf("Please hit Enter to close the program");
         }      

      getchar (); /* Add this line to stop the screen from closing immediately. */
      return 0;

}
>> Infinity08: The program compiles without problems and runs, but if i put in a letter the command window disappears, if i enter a number it works? Any ideas?

Just add this line before the return 1 :

      getchar (); /* Add this line to stop the screen from closing immediately. */

You already had that line at the end of your application.
Do you understand what the code I added does ? If not, then please say so ... there's no point in just taking code without understanding what it does and why ...
Its supposed to scan for the users input, correct? It's still disappearing though, even with the getchar(), it displays the error that it  is an invalid float value but instantly disappears :-( I'm soorry to seem so dumb.
Try adding a

system("PAUSE");

instead.
the compiler we are required to use, does not like that command it keeps erroring out when i compile.
>> it displays the error that it  is an invalid float value but instantly disappears :-( I'm soorry to seem so dumb.

Yep :) That's logical heh ... I should have seen that. Instead of getchar(), use getch()
You will need to add

#include <stdlib.h>
ok.  changing to getch(); worked, one more question and then i am done bothering you guys. How do i get it to re-display the question instead of the user having to re-run the program.
>> How do i get it to re-display the question instead of the user having to re-run the program.

As I said, you'll have to add a loop, similar to what jkr already showed

        printf("Enter the value for Chinese Yuan Conversion:");
        while(1 != scanf("%f", &CNY)) {
            fflush(stdin);
            printf("You entered an invalid value ! Enter the value for Chinese Yuan Conversion:");
        }

The fflush(stdin) was added to get rid of the wrong input, and try again.
Make sure that you understand all of this. If you don't, then don't hesitate to ask for explanation !! We will be happy to answer your questions ...
I am so confused. Can you explain where that would fit into the program that I currently have? I had a hard time understanding what he was pointing towards, but I am understanding what you are having me try, but I am not quite sure where the while statement should fit? Here is what I have that is working, other than not asking for input again after the invalid value?

/*********************************************************
Currency Conversion Program
Assignment Description: Accept one input currency,
then display in US Dollars
Name: Jessie Cochran

Course Information: Programming Concepts-CSS-561
      Course Details: Introduction to Programming
     
Assignment No:  Week Five Assignment

Created:
    Started:  7/18/2007
    End Date: 7/28/2007
   
Modifications:
Ver1:  Originally i had the week six and five assignments confused
Ver2:  Skimmed this program down to meet the requirements
Ver3:  Kept the ending statements thanking user for using my program
Ver4:  Realized I didn't meet the requirements. worked in the error checking
************************************************************/

#include <stdio.h>
#include <ctype.h>
int main (void)
{

/* Below are the abbreviations used for program */

/* Used the following website to find the conversion */
/* http://www.x-rates.com/calculator.html */

float CNY; /* Variable for Chinese Yuan */

   printf("Currency Conversion\n"); /* Title of Program */
   printf("-------------------\n"); /* line of dashes for separation */  
   printf("\n"); /* insert a blank line */
   printf("Week Five Assignment CSS-561\n"); /* Assignment Week */
   printf("Jessie Cochran\n");  /* My Name */
   printf("\n"); /* insert a blank line */
   printf("Please input an amount to convert\n");
   printf("in Chinese Yuan\n"); /* Asking user to choose from a list of choices */
   printf("\n"); /* insert a blank line */

   printf("\n"); /* insert a blank line */

           
            printf("Enter the value for Chinese Yuan Conversion: ");
           
            if (1 != scanf("%f",&CNY)) {
                printf("You entered an invalid float value !");
                getch();
                return 1;
            }
           
            printf("\n");/* insert a blank line */
            printf("\nThe US Dollar Equivalent is ");
            printf("%f", CNY/7.5948); /* Math calculation */
           

   printf("\n");
         
         {
         printf("This is the end of my program");
         printf("\n");/* insert a blank line */
         printf("\n");/* insert a blank line */
         printf("I Hope you enjoyed using my conversion calculator");
         printf("\n");/* insert a blank line */
         printf("\n");/* insert a blank line */
         printf("Please hit Enter to close the program");
         }      

      getchar (); /* Add this line to stop the screen from closing immediately. */
      return 0;

}
>> Can you explain where that would fit into the program that I currently have?

Well, currently, the if statement with the scanf asks for the user input, and if it's not valid, ends the program.

You wanted to replace that with code that does not end the program, but asks for input again when an invalid input was given by the user. So, you'll have to replace the whole if statement with the piece of code I posted (with the while loop).

In case you don't know about if statements and while loops yet, then check out this tutorial :

        http://www.cplusplus.com/doc/tutorial/control.html

It's an interesting read, and should help you understand the code better.

After reading that, is there still something that is unclear ? Then please tell me, and I'll explain it.
I understand what it wants me to do and i think i have it in the right place but something is missing. Cause when it asks me to input again it disappears after i enter anything and doesn't display the number?

 printf("Enter the value for Chinese Yuan Conversion:");
           
            while(1 != scanf("%f", &CNY)) {
            fflush(stdin);
           
            printf("You entered an invalid value ! Enter the value for Chinese Yuan Conversion:");
           
                getch();
                return 1;
            }
That's because you kept this part :
           
                getch();
                return 1;

You should have replaced the whole if :

            if (1 != scanf("%f",&CNY)) {
                printf("You entered an invalid float value !");
                getch();
                return 1;
            }

with the while :

        printf("Enter the value for Chinese Yuan Conversion:");
        while(1 != scanf("%f", &CNY)) {
            fflush(stdin);
            printf("You entered an invalid value ! Enter the value for Chinese Yuan Conversion:");
        }

The getch() waits for the user to press a key. The return 1 exits the program. You don't want either of those to happen if you want the user to try again.
I've got the impression that you don't understand the code completely. Did you read the tutorial on if's and loops that I posted ? It's a really interesting read.

If you want, I can also explain the code line by line ... just say the word ;)
I believe i understand it more. It just takes me time. I am a PC Support tech and am much better with the hands on stuff, not the behind the scenes stuff :-( If you can explain what the while statement is doing, i would really appreciate it. It worked by the way, once i got those out of there. THANK YOU SO MUCH!
ASKER CERTIFIED SOLUTION
Avatar of Infinity08
Infinity08
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
much more sense. i am going to paste this into a word doc and keep it for future ref. THANK YOU FOR YOUR PATIENCE!!!!
No problem :) Glad to be of assistance !