Discussion Locked

C program

0 helpful
3 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

The program below needs to read from a file instead of input from a user. Can someone rewrite this program so it reads validation and user input from a file instead of keyboard thanks.

//---------------------------------------------------------------------------

#pragma argsused
#include
#include
#include
#include

int main(int argc, char* argv[])
{
char *currency[5]={"Japan 108.36 Yen","Mexico 9.70 Peso's ","UnitedKingdom 0.70 Pounds","European 1.1967 Euros"};
FILE *fp;
int currencies;
menu: //display menu
printf("Choose the country you would like to convert to U.S. dollars\n");
printf("1- Japan\n");
printf("2- Mexico\n");
printf("3- HongKong\n"); printf("4- UnitedKingdom\n");
printf("5- European\n");
printf("0- to quit\n");

scanf("%d",¤cies);

//validate
if (currencies < 0||currencies >5)
{
printf("\nYou have chosen an invalid selection, please select 1-5 again.\n\n");
goto menu;
}
clrscr();
printf("One U.S. dollar is equivalent to %s\n\n",currency[currencies-2]);

getchar();
getchar();

return 0;
}
//---------------------------------------------------------------------------

3 replies

by bill_h

The code below demonstrates how to use a file for user input. This sample only reads the *first* character from the file...if you need to read more, you could either read it in char by char, and build an array, or use another function (such as fgets) to read in strings.

#include
#include

FILE *stream;
int numread,numclosed,currencies;

void main( void )
{
char *currency[5]={"Japan 108.36 Yen","Mexico 9.70 Peso's "," Hong Kong 7.80 Dollars","UnitedKingdom 0.70 Pounds","European 1.1967 Euros"};

// Open file as stream for read-only
// fails if file does not exist)
if( (stream = fopen( "Currency.Txt", "r" )) == NULL )
{
printf( "Cannot open 'Currency.Txt'...\n" );
} //Read in one char and subtract 48
//(Convert ASCII value to numeric)
currencies = fgetc(stream)-48;
printf("Value: %d\n",currencies);

//Validate against currency values
if (currencies < 1 || currencies > 5)
{ //Value out of range
printf("\nFile 'Currency.Txt' contains an invalid value.\n");
printf("Please re-create file 'Currency.Txt' and try again...\n\n");
printf("Valid country codes are:\n");
printf("1- Japan\n");
printf("2- Mexico\n");
printf("3- HongKong\n");
printf("4- UnitedKingdom\n");
printf("5- European\n");
}
else
{
//Retrieve string from array using input value
printf("One U.S. dollar is equivalent to %s\n\n",currency[currencies-1]);
}
//Close stream
numclosed = fclose(stream);
}

This discussion is closed to new replies.