• C

Structured Array from Input File

Hello, I am trying to change my program below to use data from an input file, "currv.txt" rather than have the names and conversion rates hard coded in the program.  I can open the file and have added code for opening, but I am having trouble figuring out how to write a structured array and using the data from it within the program.  The input file will only contain the following information:

Australia 1.28601
Canada 1.235
Japanese 108.83
British Pound .547465
Mexican Paso 10.785

Any help or direction would be appreciated, Thank you!


////////////////////////////////////////////////////////////////
/*  Currency Conversion program.  Displays title of program,  */
/*  Provides user input of currency amount and choice of five */
/*  currencies to convert US Dollars into.  Converts currency */
/*  into countries currecy and outputs amount.                */
////////////////////////////////////////////////////////////////

/*Includes for program*/
#include <stdio.h>
#include <math.h>


/*Defined Currencies*/
#define intAussie 1.28601      //Australian dollar exchange rate from U.S. Dollar
#define intCanada 1.235       //Canadian dollar exchange rate from U.S. Dollar
#define intYen 108.83      //Japanese Yen exchange rate from U.S. Dollar
#define intPound .547465      //British Pound exchange rate from U.S. Dollar
#define intPaso 10.785       //Mexican Paso exchange rate from U.S. Dollar

/*Main Program*/
int main(void)
{

char ifilename[] = "currv.txt"; //Input File Name
char iname[20];  //Name of Currency from Input
int inum;        //Currency Conversion Rate from Input

float intAmount;
int intMenu; //define user menu entry

/*Open Input File and Read*/
FILE *ifp;

ifp = fopen(ifilename, "r");
while (fscanf(ifp,"%s %d",iname,&inum) != EOF)
if( ifp == NULL )  // Makes sure we can open the file without an error.
{
printf("Error opening file: %s", ifilename);
exit(0);
}
   


/*User Entry for Dollar Amount*/

printf("\n\nCurrency Conversion\n\n");  //print program title
printf("Enter U.S. Dollar amount to convert:"); //User-Friendly instructions for entry
printf(" $__________\b\b\b\b\b\b\b\b\b\b"); //User entry area with backspace to write over underline
scanf ("%f", &intAmount);  //collection of user entry

/*Menu for choosing conversion*/
printf("\n\nThank you, Which currency would you like your $%.2f USD. Converted into?\n\n", intAmount); //menu header
printf("\t1. Australian\n");  //Australian Menu Choice
printf("\t2. Canadian\n");  //Canadian Menu Choice
printf("\t3. Japenese Yen\n");  //Japanese Yen Menu Choice
printf("\t4. British Pounds\n");  //British Pound Menu Choice
printf("\t5. Mexican Pasos\n\n");  //Mexican Paso Menu Choice
printf("Select One: _\b"); //User Menu Entry area
intMenu = getchar();  //collection of user menu entry

/*Condition for error checking*/
while ((intMenu < '1' || intMenu > '5') && intMenu != '5' ) //User selection error checking
{
printf("Error in choice. Please Choose an option from within the menu list.(1-5)\n"); //user instruction
printf("Select: _\b"); //Entry area for retry selection
intMenu = getchar();  //collection of user menu entry selection
}
switch (intMenu)
{

/*Perform conversion calculations and print*/
case '1' : printf("\n\nYour conversion is:\n\n\t$%.2f of U.S. Currency is equal to $%.2f Australian\n\n", intAmount, intAmount * intAussie);  //convert and print to Australian dollar
break;
case '2' : printf("\n\nYour conversion is:\n\n\t$%.2f of U.S. Currency is equal to $%.2f Canadian\n\n", intAmount, intAmount * intCanada);  //convert and print to Canadian dollar
break;
case '3' : printf("\n\nYour conversion is:\n\n\t$%.2f of U.S. Currency is equal to $%.2f Yen\n\n", intAmount, intAmount * intYen);  //convert and print to Japanese Yen
break;
case '4' : printf("\n\nYour conversion is:\n\n\t$%.2f of U.S. Currency is equal to $%.2f Pounds\n\n", intAmount, intAmount * intPound);  //convert and print to British Pound
break;
case '5' : printf("\n\nYour conversion is:\n\n\t$%.2f of U.S. Currency is equal to $%.2f Pasos\n\n", intAmount, intAmount * intPaso);  //convert and print to Mexican Paso

}

/*Close Input File*/
fclose(ifp);


return 0;
}
sweetbeeAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Harisha M GEngineerCommented:
Hi sweetbee,
   
    You should use %f for float.. not %d to read currency value

Bye
---
Harish
Jaime OlivaresSoftware ArchitectCommented:
Just a little preliminar correction. It is not:
       ("\t5. Mexican Pasos\n\n");  //Mexican Paso Menu
change to:
       ("\t5. Mexican Pesos\n\n");  //Mexican Peso Menu
-----------------------------

You need to declare proper struct to store you info:

typedef struct {
    char iname[20];  //Name of Currency from Input
    float inum;        //Currency Conversion Rate from Input  //Declare as float
} TCurrency;

Then you can declare an array to store all currency information:
TCurrency arrCurrency[5];  // Will store 5 structures

You will need to use for(;;) loops many times to traverse your array:
- When loading information from textfile to array
- When presenting the menu
- When doing conversion
This way you will avoid all these repetitive task in your code, like that switch() {}
Fernando SotoRetiredCommented:
Made some changes to your code to get it to work with a structure. You will need to find a better way of selecting the structure entry for the contry. I used the fact that the menu entry number and the order I was reading it from the file were the same, do not use it that way. Hope this helps.

/*Includes for program*/
#include <stdio.h>
#include <math.h>


typedef struct _CurrencyConversion
{
      char  Country[15];
    float Exchange;
} CurConv;

/*Main Program*/
int main(void)
{
      CurConv curconv[5];
      char ifilename[] = "c:\\Temp\\CurrencyConversion.txt"; //Input File Name
      char iname[20];  //Name of Currency from Input
      int  inum;        //Currency Conversion Rate from Input
      int  index = 0;   // Index into the _CurrencyConversion structure

      float intAmount;
      int        intMenu; //define user menu entry

      /*Open Input File and Read*/
      FILE *ifp;

      ifp = fopen(ifilename, "r");

      while (fscanf(ifp,"%s %f",curconv[index].Country, &curconv[index].Exchange) != EOF)
      {
            if( ifp == NULL )  // Makes sure we can open the file without an error.
            {
                  printf("Error opening file: %s", ifilename);
                  //exit(0);
            }
            index++;
      }
   


      /*User Entry for Dollar Amount*/

      printf("\n\nCurrency Conversion\n\n");  //print program title
      printf("Enter U.S. Dollar amount to convert:"); //User-Friendly instructions for entry
      printf(" $__________\b\b\b\b\b\b\b\b\b\b"); //User entry area with backspace to write over underline
      scanf ("%f", &intAmount);  //collection of user entry

      /*Menu for choosing conversion*/
      printf("\n\nThank you, Which currency would you like your $%.2f USD. Converted into?\n\n", intAmount); //menu header
      printf("\t1. Australian\n");  //Australian Menu Choice
      printf("\t2. Canadian\n");  //Canadian Menu Choice
      printf("\t3. Japenese Yen\n");  //Japanese Yen Menu Choice
      printf("\t4. British Pounds\n");  //British Pound Menu Choice
      printf("\t5. Mexican Pasos\n\n");  //Mexican Paso Menu Choice
      printf("Select One: _\b"); //User Menu Entry area
      intMenu = getchar();  //collection of user menu entry

      /*Condition for error checking*/
      while ((intMenu < '1' || intMenu > '5') && intMenu != '5' ) //User selection error checking
      {
            printf("Error in choice. Please Choose an option from within the menu list.(1-5)\n"); //user instruction
            printf("Select: _\b"); //Entry area for retry selection
            intMenu = getchar();  //collection of user menu entry selection
      }      

      // You will need a better way to get the right entry into the array of structures
      // The reason this will work is because the menu selection is in the same order as
      // the entries in the structure.
      switch (intMenu)
      {

            /*Perform conversion calculations and print*/
            case '1' :
                  index = 0;
                  printf("\n\nYour conversion is:\n\n\t$%.2f of U.S. Currency is equal to $%.2f Australian\n\n", intAmount, intAmount * curconv[index].Exchange);  //convert and print to Australian dollar
                  break;
            case '2' :
                  index = 1;
                  printf("\n\nYour conversion is:\n\n\t$%.2f of U.S. Currency is equal to $%.2f Canadian\n\n", intAmount, intAmount * curconv[index].Exchange);  //convert and print to Canadian dollar
                  break;
            case '3' :
                  index = 2;
                  printf("\n\nYour conversion is:\n\n\t$%.2f of U.S. Currency is equal to $%.2f Yen\n\n", intAmount, intAmount * curconv[index].Exchange);  //convert and print to Japanese Yen
                  break;
            case '4' :
                  index = 3;
                  printf("\n\nYour conversion is:\n\n\t$%.2f of U.S. Currency is equal to $%.2f Pounds\n\n", intAmount, intAmount * curconv[index].Exchange);  //convert and print to British Pound
                  break;
            case '5' :
                  index = 4;
                  printf("\n\nYour conversion is:\n\n\t$%.2f of U.S. Currency is equal to $%.2f Pasos\n\n", intAmount, intAmount * curconv[index].Exchange);  //convert and print to Mexican Paso

      }      

      /*Close Input File*/
      fclose(ifp);
      return 0;
}

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Your Guide to Achieving IT Business Success

The IT Service Excellence Tool Kit has best practices to keep your clients happy and business booming. Inside, you’ll find everything you need to increase client satisfaction and retention, become more competitive, and increase your overall success.

Jaime OlivaresSoftware ArchitectCommented:
You must combine both structures:

typedef struct
{
    char  Country[15];
    char Currency[20];  //Name of Currency from Input
    float Exchange;
} TCurrency;

TCurrency curconv[5];
// fill the array properly


so you can elmininate the switch/case with something like this:
Instead of cases like:
         case '1' :
               index = 0;
               printf("\n\nYour conversion is:\n\n\t$%.2f of U.S. Currency is equal to $%.2f Australian\n\n", intAmount, intAmount * curconv[index].Exchange);  //convert and print to Australian dollar
               break;
 
Eliminate all switch and use this unique code portion:
               index = intMenu-1;
               printf("\n\nYour conversion is:\n\n\t$%.2f of U.S. Currency is equal to %.2f %s\n\n", intAmount, intAmount * curconv[index].Exchange, curconv[index].Currency);

Also notice that not all currencies use symbol $
Fernando SotoRetiredCommented:
Two things, first in my code above place the following code line just before the switch statement.

index = intMenu - 49;
The reason is that the getchar() returns an integer value for the ASCII character which is 49 for the ASCII character 1. So subtracting 49 will put us at the correct index into the structure.

The scond thing is when using the fscanf(ifp,"%s %f",curconv[index].Country, &curconv[index].Exchange) the format specifier %s will parse the input at white space. Therefore the input file should have no white space in the name. So in your example the input file should look something like this.

Australia 1.28601
Canada 1.235
Japanese 108.83
British-Pound .547465     <--- No spaces in name
Mexican-Paso 10.785      <--- No spaces in name

Fernando SotoRetiredCommented:
Also remove all the other ndex = ?; from all the case statements.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C

From novice to tech pro — start learning today.