• C

Error Checking Capability

I am having a difficult time trying to figure out how to add an error checking function to the following code.   Basically if something other than the proper money format is entered I would like it to loop back to the menu screen as well as giving an error message.  I am new to programming in C as well as Experts Exchange, so if something is wrong please let me know.

#include <stdio.h>
#define aus      1.32294          /* Austrailian Conversion Rate per 1 USD*/
#define bri       .5332           /* British Conversion Rate per 1 USD*/
#define can      1.27046        /* Canadian Conversion Rate per 1 USD*/
#define eur      .791105        /* Euro Conversion Rate per 1 USD*/
#define sws      1.22340        /* Swiss Franc Conversion Rate per 1 USD*/
int main(void)
{
  float usd;               /* Currency in US Dollars  */
  float caus;                      /* Converted from USD to Austrailian */
  float cbri;                       /* Converted from USD to British */
  float ccan;                      /* Converted from USD to Canada */
  float ceur;                      /* Converted from USD to Euro  */
  float csws;                      /* Converted from USD to Swiss */
  printf("\n");
  printf("\t\t Currency Conversion Program Version 1.1\n");
  printf("\n");
  printf("This program converts an amount of USD to a correct value in the following Five (5) currencies:\n");
  printf("\n");
  printf("\t\t 1. Austrailian Dollars\n");
  printf("\t\t 2. British Pounds\n");
  printf("\t\t 3. Canadian Dollars\n");
  printf("\t\t 4. Euro\n");
  printf("\t\t 5. Swiss Francs.\n");
  printf("\n");
  printf("Please enter the amount of USD to be converted in the $000.00 format: \n");
  scanf("%f", &usd);  /* User enters a dollar amount  */  THIS IS WHERE I AM TRYING TO GET THE ERROR CHECK AT
  caus = (float) usd * aus;   /* Converts USD to Austrailian Dollars       */
  cbri = (float) usd * bri;   /* Converts USD to British Pounds*/
  ccan = (float) usd * can;   /* Converts USD to Canadian Dollars*/
  ceur = (float) usd * eur;   /* Converts USD to Euro*/
  csws = (float) usd * sws;   /* Converts USD to Swiss Francs    */
  printf("\n");
  printf("\t\t $%.2f is equal to: \n", usd,); /*Displays the amount in U.S. Dollars being converted */
  printf("\t\t $%.2f in Austrailian Dollars. \n", caus, aus);  /*Displays the USD amount in Austrailian Dollars*/
  printf("\t\t $%.2f in British Pounds. \n", cbri, bri);  /*Displays the USD amount in British Pounds*/
  printf("\t\t $%.2f in Canadian Dollars. \n", ccan, can); /*Displays the USD amount in Canadian Dollars*/
  printf("\t\t $%.2f in Euro. \n", ceur, eur);  /*Displays the USD amount in Euro*/
  printf("\t\t $%.2f in Swiss Francs. \n", csws, sws);  /*Displays the USD amount in Swiss Francs*/
  return 0;
}
patrickpierce27Asked:
Who is Participating?
 
Kent OlsenData Warehouse Architect / DBACommented:

:)

if (isdigit (A) && isdigit (B) && C == '\n\)

should be:

if (isdigit (A) && isdigit (B) && C == '\n')



sscanf (Buffer, "%d %c %c %c", &I, &A, &B, &C);

allows spaces in the amount.  100 0 0 would be accepted with this format.  100.00 would not.

Try:

sscanf (Buffer, "%d.%c%c%c", &I, &A, &B, &C);


Kent
0
 
Kent OlsenData Warehouse Architect / DBACommented:

Hi Patrick,

A simple, but effective, solution is to wrap the lines between the first prinf() statement and the scanf() statement in a while() loop.

After the scanf() executes simply check that the value is in range.  If not, the while() contraint will repeat all of the code within it.  If the value is in range, a break statement will exit the while() loop and you'll print your answer.


Good Luck!
Kent
0
 
Harisha M GCommented:
Hi patrickpierce27,
   
    How do you want to check ?

    if(/*error*/)
    {
        main();
        return 0;
    }
    else
    {
        ...
    }

Bye
---
Harish
0
Creating Active Directory Users from a Text File

If your organization has a need to mass-create AD user accounts, watch this video to see how its done without the need for scripting or other unnecessary complexities.

 
Harisha M GCommented:
patrickpierce27,
    Do you want to check whether the code
    1. is out of range
    2. contains invalid characters
    3. cibtains no decimal point

    ??
0
 
patrickpierce27Author Commented:
I am wanting it to check to see if the input is in a dollar format, i.e 123.56.  If not then I want it to loop back to the intitial prompt asking for input.  Lets say someone enters abcde...
0
 
Harisha M GCommented:
What if it is 123 ?
0
 
Kent OlsenData Warehouse Architect / DBACommented:

Hi Patrick,

Read the data as a string.  You're using scanf(), use fgets().  gets() is a wrapper around fgets() that reads from standard input, and your instructor may well tell you to use it, but none of the experts here will.  gets() is a great way to get your program to misfire.

  fgets (Buffer, BUFFER_LENGTH, stdin);

Now use sscanf() to make sure that the input string is exactly as you want.

  EOLCharacter = 0;
  sscanf (" %d.%02d %c", &Int1, &Int2, &EOLCharacter);

If the input string is in exactly the format that you want, '\n' will be written to the variable EOLCharacter.  (This string does allow leading and trailing spaces.)

Then call sscanf() again to convert the string to a number and keep right on going....


Kent
0
 
patrickpierce27Author Commented:
If possible I would also like that to return an error.  Basically I am wanting an input to be 000.00 or 0.00 or whatever decimal dollar format.  I have tried a while statement, but am not for sure how to make it work.  

I tried something like int=usd,  then the print statements and a while statement like while usd = char.... however that was wrong and I am at a loss where to go next.
0
 
Kent OlsenData Warehouse Architect / DBACommented:


If you're willing to accept variations of the amount (integer, only 1 decimal point, etc)  simply use a different format string.

Try " %f.2 %c" and see what happens.


Good Luck,
Kent
0
 
Harisha M GCommented:
scanf("%5.2f",&usd);

shoudl except max 999.99 from 000.000

You should declare all float-s as unsigned floats
0
 
patrickpierce27Author Commented:
Okay Kent,

I added the comment in the below text.

printf("Please enter the amount of USD to be converted in the $000.00 format: \n");
scanf("%%f.2 %c", &usd);  /* User enters a dollar amount  */

Now if any number is entered it will display the next prmpt but with zero values, however if a letter is entered the program exits and does not allow a retry.  I am in agreement that I need to use a while statement, but I do not know how to get it to work.  I apologize for the repetive questions on this, but I have read hours of language tutorials and i am just not getting it.

0
 
Kent OlsenData Warehouse Architect / DBACommented:

Hi Patrick,

>scanf("%5.2f",&usd);

Will not do what you want.  You'll need a smarter format string than this.

The string above will allow things like "123.45X".  Certainly not what you want.

Kent
0
 
Harisha M GCommented:
Kent, What is X there ?
0
 
Kent OlsenData Warehouse Architect / DBACommented:

X is anything.  scanf() will properly grab the floating point value and ignore anything else.  Trailing data will be ignored, even though it is really an error.


Hi Patrick,

I've run some scanf() tests on a couple of systems and it seems that floating point conversion may have its own issue.  The string that I sent above doesn't always work.  The following one does:

  sscanf (Buffer, "%d\.%c%c%c", &C, &D, &E, &F);

If the proper value is in Buffer, F will contain a new-line character ('\n').


To put a loop around all of this, put

  while (1)
  {

right before the first printf() statement.

Put

    if (/*  Text for valid data  */)
      break;
  }

right after the scanf() statement.


This doesn't address what is valid data.  There seems to be an issue in this thread with determining valid data.  But it does put the central part of the program into a loop.


Kent
0
 
patrickpierce27Author Commented:
Hello Everyone,

I have been able to figure out the while loop statement, but I cannot get it to work since I really cannot figure out how to check for an invalid character.  I appreciate everyones help, but I have not been able to follow some of the sujjestions.  Like I said I am really new to c programming, this is my first project and it took me awhile to get this far.

Anyway what I now have is this....
               
                while(enter statement here);
        {
        printf("Please enter the amount of USD to be converted in the $000.00 format: \n");
        scanf("%f", &usd);    /* User enters a dollar amount  */
        if (enter statement here);
            break;
        }

I assume the while statement would need to say something like while usd is equal to an invalid character it will loop.  The if statement would need to say something like usd == valid character break...

That much I am clear on, I just do not know how to make that happen....
0
 
Kent OlsenData Warehouse Architect / DBACommented:
Hi Patrick,

Yep.  There is no "easy" way in C to do what you outline.  You could write another function and call it here, but that seems a bit messy.  It would leave your code with something like this:

int
GetData (float &Amount)
{
  while (1)    /*  We still have a while loop here, breaking on good data.  */
  {
     scanf ("format string";
     if (valid)
       return (0);
  }
}

main ()
{
  float usd;
....
  GetData (&usd)
....
}

Pick your poison.  You're going to have to have a while() loop someplace.  It's just as easy to have it in the main program.

So let's go back to the last format string that I offered and use it.  It works.

The basic controls should look like the following code.  while(1) says loop forever.  The 4th line in the block is an if() statement that tests to make sure that the 3 characters after the period are digit, digit, new-line.  If that's the case, the break is executed and the while(1) loop is exited.  (This is a common technique in C.)  Note that break causes exits from within while(), for() and/or switch() statements.  It breaks exactly 1 level.

main ()
{
  float usd;
  char Buffer[100];
  int I;
  char A, B, C;
....
  while (1)
  {
    fgets (Buffer, 100 stdin);
    D = 0;
    sscanf (Buffer, "%d\.%c%c%c", &I, &A, &B, &C);
    if (isdigit (B) && isdigit (C) && D == '\n\)
      break;
  }
  sscan (Buffer, "%f", &usd);
....
}

Try merging this code with yours.  I think you'll find that it works just fine.
Kent
0
 
patrickpierce27Author Commented:
Okay Kent here is what I have now......


char Buffer[100];
int I;
char A, B, C;
 
        
        while (1)
        {
        fgets( Buffer, 100 stdin);
          D = 0;
         printf("Please enter the amount of USD to be converted in the $000.00 format: \n");
        sscanf (Buffer, "%d\.%c%c%c", &I, &A, &B, &C);
          if (isdigit (B) && isdigit (C) && D == '\n\);
            break;
            }
        sscan (Buffer, "%f", &usd);


And here is the first parse error that I am getting.....


c: line 57: Parse Error, expecting `')'' or `',''
'{ fgets( Buffer, 100 (&_files[0]))'
aborting compile


DId I add the code to teh correct place?  If so what does the fgets not work correctly?
0
 
Kent OlsenData Warehouse Architect / DBACommented:

Simple typo.  :)  There should be a comma after the '100'.

Also, you should probably print your message before the call to fgets().

        while (1)
        {
          printf("Please enter the amount of USD to be converted in the $000.00 format: \n");
          fgets( Buffer, 100, stdin);
          D = 0;
          sscanf (Buffer, "%d\.%c%c%c", &I, &A, &B, &C);
          if (isdigit (B) && isdigit (C) && D == '\n\);
           break;
         }
         sscan (Buffer, "%f", &usd);


To use isdigit(), you'll also need to include ctypes.h.

#include <ctype.h>


Kent
0
 
patrickpierce27Author Commented:
Hello Kent,  

I am still receiving errors when I try the following code.        

Below is what i have in the source file...

while(1)
       {
        printf("Please enter the amount of USD to be converted in the $000.00 format: \n");
        fgets( Buffer, 100, stdin);
        D = 0;
        sscanf (Buffer, "%d\.%c%c%c", &I, &A, &B, &C);
        if (isdigit (B) && isdigit (C) && D == '\n\);
        break;
        }
        sscan (Buffer, "%f", &usd);


Here are the errors that I am getting.

     1.  line 59: variable 'D' not found 'D = 0'  ( I assume I am getting this since the char A, B, C; does not have D in it, but I could be wrong.)
     2.  I comment out the D=0 and now I receive this one.....
          line 60: lexical: unknown escape sequence `\.''sscanf (Buffer, "%d\.%c%c%c", &I, &A, &B, &C)'
     3.  After commenting out the above one I get....line 61: variable 'D' not found 'if (isdigit (B) && isdigit (C) && D == '\n\)'  (If line 59 could be resolved I imagine this one would take care of itself.



That appears to be it on the errors, I have tried different settings in the lines but none have worked.  I have reposted what you sujjested so you know where I stand at the moment.
0
 
Kent OlsenData Warehouse Architect / DBACommented:

Change:

      if (isdigit (B) && isdigit (C) && D == '\n\);

to be:

      if (isdigit (A) && isdigit (B) && C == '\n\)


Note that the trailing ';' is also removed!

Kent
0
 
patrickpierce27Author Commented:
Kent I will try that, but reading the command seems to me that it will take care of the unrecognized character but not the illegal escape sequence that I am still getting.  Do you know why I would be getting the illegal escape sequence?  I have included the following in my code for library's so I do not know.

#include <stdio.h>
#include <ctype.h>
0
 
patrickpierce27Author Commented:
Well kent that took care of the invalid characters, however I am still getting the illegal escape sequence...... Sorry to continue on with the same problem but I just cannot figure it out.
0
 
Kent OlsenData Warehouse Architect / DBACommented:


Strange, it would appear that your compiler doesn't like the \. in the format string.

Try removing the '\' from the string, leaving "%d.%c%c%c".


Kent
0
 
patrickpierce27Author Commented:
Yes I was one step ahead of you on that one....


I played around on Google and changed a few things in that line and got it to work, but as luck would have it I get another error for the line below.


sscanf (Buffer, "%d %c %c %c", &I, &A, &B, &C);
if (isdigit (A) && isdigit (B) && C == '\n\)

Now the SSCANF seems to work, although I have not ran it in a program yet.  Now the If (isdigit) is giving me fits...... From what I found online the format seems good and I am researching each error.  

If it is any help I am using mircale c compiler.

HERE IS THE ERROR>
line 61: lexical: unknown escape sequence `\)' 'if (isdigit (A) && isdigit (B) && C == '\n\) break'
0
 
patrickpierce27Author Commented:
Just a few more notes to above, I take out the \n\ and then I get a parse error instead of an unknown escape.....  which looks like this.

line 61: Parse Error
'if (isdigit (A) && isdigit (B) && C == ) break'
0
 
patrickpierce27Author Commented:
One last note, I think what was accomplished with the /n/ bit was to end the line... I changed the syntax and got that to compile.... Now when I try to build I get this....


Linker Error (Severity 4)
      Module "a" in file "c:\documents and settings\patrick pierce\desktop\programs\weekfiveone.obj"
      references unresolved external "_sscan"
      at offset 0223H in segment "_text".
0
 
Kent OlsenData Warehouse Architect / DBACommented:


sscan should be sscanf.

Kent
0
 
patrickpierce27Author Commented:
Okay Kent I think we are almost there.  I found the sscan error then came back and saw what you posted.  Anyway the program compiles, and builds.....

I start the program just fine and get to the initial prompt.... Now no matter what is entered the program continues to loop.

So if I enter 123.56 or abcde, or 1 2 3 or whatever the program just continues to loop.  I have to enter control c to quit.  

Again I thank you for all your help on this one.
0
 
patrickpierce27Author Commented:
Okay Kent I think I figured it out.... the program appears to work... I am going to play around with it some more and then I will close this question out... I thank you for all your help... I have definately learned some stuff here.
0
 
patrickpierce27Author Commented:
Okay Kent one last question and I promise I will be done with this thread....

As far as a printf statement saying the input was incorrect where exactly should I put that so it only comes up on an incorrect prompt?

I have tried before and after the fgets as well as the sscan commands... on the fgets I get the prompt each time it is entered incorrectly and once it is entered correctly.
0
 
patrickpierce27Author Commented:
Disregard my previous post, I figured it out.... thanks again.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.