Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

C Programming - error checking

Posted on 2007-07-28
26
Medium Priority
?
241 Views
Last Modified: 2010-04-15
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;

}
0
Comment
Question by:JCochran1977
  • 13
  • 9
  • 4
26 Comments
 
LVL 53

Expert Comment

by:Infinity08
ID: 19585632
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.
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 19585634
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 ...
0
 
LVL 86

Expert Comment

by:jkr
ID: 19585693
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 */
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 1

Author Comment

by:JCochran1977
ID: 19585747
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?
0
 
LVL 86

Expert Comment

by:jkr
ID: 19585769
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) {
//...
}
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 19585775
>> 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.
0
 
LVL 1

Author Comment

by:JCochran1977
ID: 19585865
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;

}
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 19585872
>> 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.
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 19585877
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 ...
0
 
LVL 1

Author Comment

by:JCochran1977
ID: 19585920
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.
0
 
LVL 86

Expert Comment

by:jkr
ID: 19585928
Try adding a

system("PAUSE");

instead.
0
 
LVL 1

Author Comment

by:JCochran1977
ID: 19585952
the compiler we are required to use, does not like that command it keeps erroring out when i compile.
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 19585962
>> 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()
0
 
LVL 86

Expert Comment

by:jkr
ID: 19585964
You will need to add

#include <stdlib.h>
0
 
LVL 1

Author Comment

by:JCochran1977
ID: 19586001
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.
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 19586030
>> 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.
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 19586032
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 ...
0
 
LVL 1

Author Comment

by:JCochran1977
ID: 19586047
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;

}
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 19586063
>> 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.
0
 
LVL 1

Author Comment

by:JCochran1977
ID: 19586090
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;
            }
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 19586097
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.
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 19586100
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 ;)
0
 
LVL 1

Author Comment

by:JCochran1977
ID: 19586114
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!
0
 
LVL 53

Accepted Solution

by:
Infinity08 earned 2000 total points
ID: 19586153
>> If you can explain what the while statement is doing, i would really appreciate it.

Sure. Here's a step-by-step explanation :

        scanf("%f", &CNY)

gets the input from the user. If it's a valid float, then it's stored in the CNY variable, and scanf returns 1 (because it matched one value). If it's not a valid float (the user entered a letter for example), then scanf returns 0 (because it matched 0 values).
We are going to use that return value to decide when the user entered a correct value, and when we have to ask to try again. If the return value of the scanf statement is different from 1, then we will try again, and we will keep trying again until a valid value is given by the user.

Now, keep that in mind. I'll now explain what a while loop does. Here's a template :

        while (condition) {
            do_something();
        }
        then_do_this();

In a while loop, whatever is between the {}'s (in this case do_something() ), will be repeated as long as the condition is true. The moment the condition becomes false, we end the loop, and continue with the code after the loop (in this case then_do_this() ).

Now, for our code, the condition for the loop is that the user entered a invalid value :

        1 != scanf("%f", &CNY)

(ie. the return value of scanf is not 1). So, we put that in the while loop :

        while(1 != scanf("%f", &CNY)) {

        }

And now we just have to figure out what to put inside the {}'s. That's pretty easy : we have to tell the user that he entered an invalid value, and that he has to try again :

            printf("You entered an invalid value ! Enter the value for Chinese Yuan Conversion:");

But we also have to make sure that the invalid value is removed from the buffer :

            fflush(stdin);

And we combine all this into :

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

I hope it all makes a bit more sense now ?
0
 
LVL 1

Author Comment

by:JCochran1977
ID: 19586164
much more sense. i am going to paste this into a word doc and keep it for future ref. THANK YOU FOR YOUR PATIENCE!!!!
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 19586168
No problem :) Glad to be of assistance !
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
Examines three attack vectors, specifically, the different types of malware used in malicious attacks, web application attacks, and finally, network based attacks.  Concludes by examining the means of securing and protecting critical systems and inf…
The goal of this video is to provide viewers with basic examples to understand recursion in the C programming language.
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.
Suggested Courses

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question