Question

I need help with this C code Can you explain line by line? Also can you...

I need help with this C code

Can you explain line by line?
Also can you explain to me the flow of the code, like the flow of how the compiler reads it. I need to present this and I want to make sure I understand every single line of it.

Thank you!

/*
* Converts measurements given in one unit to any other unit of the same
* category that is listed in the database file, units.txt.
* Handles both names and abbreviations of units.
*/
#include <stdio.h>
#include <string.h>
#define NAME_LEN 30       /* storage allocated for a unit name */
#define ABBREV_LEN 15       /* storage allocated for a unit abbreviation */
#define CLASS_LEN 20       /* storage allocated for a measurement class */
#define NOT_FOUND -1       /* value indicating unit not found */
#define MAX_UNITS 20       /* maximum number of different units handled */

typedef struct
{               /* unit of measurement type */
char name[NAME_LEN];       /* character string such as "milligrams" */
char abbrev[ABBREV_LEN];   /* shorter character string such as "mg" */
char class[CLASS_LEN];   /* character string such as "pressure",
               "distance", "mass" */
double standard;       /* number of standard units equivalent to this unit */
} unit_t;

int fscan_unit (FILE * filep, unit_t * unitp);
void load_units (int unit_max, unit_t units[], int *unit_sizep);
int search (const unit_t units[], const char *target, int n);
double convert (double quantity, double old_stand, double new_stand);

int
main (void)
{
unit_t units[MAX_UNITS];   /* units classes and conversion factors */
int num_units;       /* number of elements of units in use */
char old_units[NAME_LEN],   /* units to convert (name or abbrev) */
new_units[NAME_LEN];   /* units to convert to (name or abbrev) */
int status;           /* input status */
double quantity;       /* value to convert */

int old_index,       /* index of units element where
               old_units found */
new_index;           /* index where new_units found */

/* Load units of measurement database */
load_units (MAX_UNITS, units, &num_units);

/* Convert quantities to desired units until data format error
(including error code returned when q is entered to quit) */
printf ("Enter a conversion problem or q to quit.\n");
printf ("To convert 25 kilometers to miles, you would enter\n");
printf ("> 25 kilometers miles\n");
printf (" or, alternatively,\n");
printf ("> 25 km mi\n> ");

for (status = scanf ("%lf%s%s", &quantity, old_units, new_units);
status == 3;
status = scanf ("%lf%s%s", &quantity, old_units, new_units))
{
printf ("Attempting conversion of %.4f %s to %s . . . \n",
   quantity, old_units, new_units);
old_index = search (units, old_units, num_units);
new_index = search (units, new_units, num_units);
if (old_index == NOT_FOUND)
   printf ("Unit %s not in database\n", old_units);
else if (new_index == NOT_FOUND)
   printf ("Unit %s not in database\n", new_units);
else if (strcmp (units[old_index].class, units[new_index].class) != 0)
   printf ("Cannot convert %s (%s) to %s (%s)\n",
       old_units, units[old_index].class, new_units,
       units[new_index].class);
else
   printf ("%.4f%s = %.4f %s\n", quantity, old_units,
       convert (quantity, units[old_index].standard,
           units[new_index].standard), new_units);
printf ("\nEnter a conversion problem or q to quit.\n> ");
}
return (0);
}

/*
* Gets data from a file to fill output argument
* Returns standard error code: 1 => successful input, 0 => error,
* negative EOF value => end of file
*/
int
fscan_unit (FILE * filep,   /* input - input file pointer */
   unit_t * unitp)   /* output - unit_t structure to fill */
{
int status;

status = fscanf (filep, "%s%s%s%lf", unitp->name,
       unitp->abbrev, unitp->class, &unitp->standard);

if (status == 4)
status = 1;
else if (status != EOF)
status = 0;

return (status);
}

/*
* Opens database file units.txt and gets data to place in units until end
* of file is encountered. Stops input prematurely if there are more than
* unit_max data values in the file or if invalid data is encountered. */

void
load_units (int unit_max,   /* input - declared size of units */
   unit_t units[],   /* output - array of data */
   int *unit_sizep)   /* output - number of data values
               stored in units */
{
FILE *inp;
unit_t data;
int i, status;

/* Gets database of units from file */
inp = fopen ("units.txt", "r");
i = 0;

for (status = fscan_unit (inp, &data);
status == 1 && i < unit_max; status = fscan_unit (inp, &data))
{
units[i++] = data;
}
fclose (inp);

/* Issue error message on premature exit */
if (status == 0)
{
printf ("\n*** Error in data format ***\n");
printf ("*** Using first %d data values ***\n", i);
}
else if (status != EOF)
{
printf ("\n*** Error: too much data in file ***\n");
printf ("*** Using first %d data values ***\n", i);
}

/* Send back size of used portion of array */
*unit_sizep = i;
}

/*
* Searches for target key in name and abbrev components of first n
* elements of array units
* Returns index of structure containing target or NOT_FOUND
*/
int
search (const unit_t units[],   /* array of unit_t structures to search */
   const char *target,   /* key searched for in name and abbrev
               components */
   int n)           /* number of array elements to search */
{
int i, found = 0,       /* whether or not target has been found */
where;           /* index where target found or NOT_FOUND */

/* Compare name and abbrev components of each element to target */
i = 0;
while (!found && i < n)
{
if (strcmp (units[i].name, target) == 0 ||
   strcmp (units[i].abbrev, target) == 0)
   found = 1;
else
   ++i;
}
/* Return index of element containing target or NOT_FOUND */
if (found)
where = i;

else
where = NOT_FOUND;
return (where);
}

/*
* Converts one measurement to another given the representation of both
* in a standard unit. For example, to convert 24 feet to yards given a
* standard unit of inches: quantity = 24, old_stand = 12 (there are 12
* inches in a foot), new_stand = 36 (there are 36 inches in a yard),
* result is 24 * 12 / 36 which equals 8 */
double
convert (double quantity,   /* value to convert */
   double old_stand,   /* number of standard units in one of
               quantity's original units */
   double new_stand)   /* number of standard units in 1 new unit */
{
return (quantity * old_stand / new_stand);
}

units.txt FILE:

miles       mi           distance       1609.3
kilometers   km           distance       1000
yards       yd           distance       0.9144
meters        m           distance       1
quarts       qt           liquid_volume       0.94635
liters       l           liquid_volume       1
gallons       gal           liquid_volume       3.7854
milliliters   ml           liquid_volume       0.001
kilograms   kg           mass           1
grams       g           mass           0.001
slugs        slugs           mass           0.14594
pounds       lb           mass           0.43592


0 0
Add a comment Improve this question Transcribed image text
Answer #1

Hi, I entered comment in all lines. just go through the code. now you can understand it properly.

- This the program of the unit converter.

- if you check main(): we are loading units array fist. using load_units function.

- Then we are taking data from the user.

- and after that, we are checking if any errors are there or not.

- and then if all things are ok are converting it to a new unit from the old unit.

/*

* Converts measurements given in one unit to any other unit of the same

* category that is listed in the database file, units.txt.

* Handles both names and abbreviations of units.

*/

#include <stdio.h>

#include <string.h>

#define NAME_LEN 30 /* storage allocated for a unit name */

#define ABBREV_LEN 15 /* storage allocated for a unit abbreviation */

#define CLASS_LEN 20 /* storage allocated for a measurement class */

#define NOT_FOUND -1 /* value indicating unit not found */

#define MAX_UNITS 20 /* maximum number of different units handled */

typedef struct

{ /* unit of measurement type */

   char name[NAME_LEN]; /* character string such as "milligrams" */

   char abbrev[ABBREV_LEN]; /* shorter character string such as "mg" */

   char class[CLASS_LEN]; /* character string such as "pressure",

             "distance", "mass" */

   double standard; /* number of standard units equivalent to this unit */

} unit_t;

/* function diclaration */

int fscan_unit (FILE * filep, unit_t * unitp); /* read data from file */

void load_units (int unit_max, unit_t units[], int *unit_sizep); /* load data from file to array */

int search (const unit_t units[], const char *target, int n); /* serch unit from array of units */

double convert (double quantity, double old_stand, double new_stand); /* convert data */

   int

main (void)

{

   unit_t units[MAX_UNITS]; /* units classes and conversion factors */

   int num_units; /* number of elements of units in use */

   char old_units[NAME_LEN], /* units to convert (name or abbrev) */

    new_units[NAME_LEN]; /* units to convert to (name or abbrev) */

   int status; /* input status */

   double quantity; /* value to convert */

   int old_index, /* index of units element where

            old_units found */

    new_index; /* index where new_units found */

   /* Load units of measurement database */

   load_units (MAX_UNITS, units, &num_units);

   /* Convert quantities to desired units until data format error

    (including error code returned when q is entered to quit) */

   printf ("Enter a conversion problem or q to quit.\n"); /* give option to user */

   printf ("To convert 25 kilometers to miles, you would enter\n"); /* give usage to user */

   printf ("> 25 kilometers miles\n");

   printf (" or, alternatively,\n");

   printf ("> 25 km mi\n> ");

   for (status = scanf ("%lf%s%s", &quantity, old_units, new_units); /* get data from user quantity old_units and new_units */

status == 3; /* status shoud be 3 because data we are reading is 3 */

status = scanf ("%lf%s%s", &quantity, old_units, new_units)) /* get data from user quantity old_units and new_units */

   {

      printf ("Attempting conversion of %.4f %s to %s . . . \n",

            quantity, old_units, new_units); /* print data that user entered */

      old_index = search (units, old_units, num_units); /* serch old unit index in units array */

      new_index = search (units, new_units, num_units); /* serch new unit index in units array */

      if (old_index == NOT_FOUND) /* if old unit not found print error */

         printf ("Unit %s not in database\n", old_units); /* print error message for old unit */

      else if (new_index == NOT_FOUND) /* if new unit not foud */

         printf ("Unit %s not in database\n", new_units); /* print error message for new unit */

      else if (strcmp (units[old_index].class, units[new_index].class) != 0) /* check if old and new unit are same print error message */

         printf ("Cannot convert %s (%s) to %s (%s)\n",

               old_units, units[old_index].class, new_units,

               units[new_index].class); /* error message for old and new unit is same */

      else

         printf ("%.4f%s = %.4f %s\n", quantity, old_units,

               convert (quantity, units[old_index].standard,

                  units[new_index].standard), new_units); /* if user entered data is same convert old to new unit and print it */

      printf ("\nEnter a conversion problem or q to quit.\n> "); /* ask user to enter again or quit by entering q */

   }

   return (0); // return to _start with 0

}

/*

* Gets data from a file to fill output argument

* Returns standard error code: 1 => successful input, 0 => error,

* negative EOF value => end of file

*/

   int

fscan_unit (FILE * filep, /* input - input file pointer */

      unit_t * unitp) /* output - unit_t structure to fill */

{

   int status; /* define variable to store fscanf status */

   status = fscanf (filep, "%s%s%s%lf", unitp->name,

         unitp->abbrev, unitp->class, &unitp->standard); /* read file using fscanf store data in structure membters */

   if (status == 4) /* status shoud be 4 because we are reading 4 data from file */

      status = 1; /* make status 1 */

   else if (status != EOF) /* if status is not end of file */

      status = 0; /* make status 0 */

   return (status); /* return status to calling function */

}

/*

* Opens database file units.txt and gets data to place in units until end

* of file is encountered. Stops input prematurely if there are more than

* unit_max data values in the file or if invalid data is encountered. */

   void

load_units (int unit_max, /* input - declared size of units */

      unit_t units[], /* output - array of data */

      int *unit_sizep) /* output - number of data values

             stored in units */

{

   FILE *inp; /* File pointer */

   unit_t data; /* unit variable data */

   int i, status; /* integer variable */

   /* Gets database of units from file */

   inp = fopen ("units.txt", "r"); /* open file units.txt for read */

   i = 0; /* initialize i with 0 */

   for (status = fscan_unit (inp, &data); /* read unit in data and get status in status */

         status == 1 && i < unit_max; /* if status is 1 then enter in side the for part and i shoud less than unit_max */

status = fscan_unit (inp, &data)) /* read unit in data and get status in status */

   {

      units[i++] = data; /* store data in units array with ith index and increment i after storing data */

   }

   fclose (inp); /* after storing all data close file */

   /* Issue error message on premature exit */

   if (status == 0) /* if status is 0 print error message */

   {

      printf ("\n*** Error in data format ***\n"); /* print data formate error */

      printf ("*** Using first %d data values ***\n", i); /* print in which index there is formate problem */

   }

   else if (status != EOF) /* if status is not EOF(end of file) means there are too much data and units array is full print error message */

   {

      printf ("\n*** Error: too much data in file ***\n"); /* print too much data error */

      printf ("*** Using first %d data values ***\n", i); /* print index */

   }

   /* Send back size of used portion of array */

   *unit_sizep = i; /* store size of array in unit_sizep referance variable */

}

/*

* Searches for target key in name and abbrev components of first n

* elements of array units

* Returns index of structure containing target or NOT_FOUND

*/

int

search (const unit_t units[], /* array of unit_t structures to search */

      const char *target, /* key searched for in name and abbrev

                components */

      int n) /* number of array elements to search */

{

   int i, found = 0, /* whether or not target has been found */

   where; /* index where target found or NOT_FOUND */

   /* Compare name and abbrev components of each element to target */

   i = 0;

   while (!found && i < n) /* If found is zero and i is less than n it will enter in while */

   {

      if (strcmp (units[i].name, target) == 0 ||

            strcmp (units[i].abbrev, target) == 0) /* check name and abbrev perameter with targes is any one is same found will 1 */

         found = 1;

      else

         ++i; // if not same i will be increment by 1

   }

   /* Return index of element containing target or NOT_FOUND */

   if (found) /* if found is 1 then give that unit idex to where */

      where = i;

   else

      where = NOT_FOUND; /* if unit not found where will have NOT_FOUND */

   return (where); /* return where(index) */

}

/*

* Converts one measurement to another given the representation of both

* in a standard unit. For example, to convert 24 feet to yards given a

* standard unit of inches: quantity = 24, old_stand = 12 (there are 12

* inches in a foot), new_stand = 36 (there are 36 inches in a yard),

* result is 24 * 12 / 36 which equals 8 */

double

convert (double quantity, /* value to convert */

      double old_stand, /* number of standard units in one of

             quantity's original units */

      double new_stand) /* number of standard units in 1 new unit */

{

   return (quantity * old_stand / new_stand); /* (24*12/36) */

}

Add a comment
Know the answer?
Add Answer to:
I need help with this C code Can you explain line by line? Also can you...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • -I need to write a program in C to store a list of names (the last...

    -I need to write a program in C to store a list of names (the last name first) and age in parallel arrays , and then later to sort them into alphabetical order, keeping the age with the correct names. - Could you please fix this program for me! #include <stdio.h> #include <stdlib.h> #include <string.h> void data_sort(char name[100],int age[100],int size){     int i = 0;     while (i < size){         int j = i+1;         while (j < size){...

  • Convert C to C++ I need these 4 C file code convert to C++. Please Convert...

    Convert C to C++ I need these 4 C file code convert to C++. Please Convert it to C++ //////first C file: Wunzip.c #include int main(int argc, char* argv[]) { if(argc ==1){ printf("wunzip: file1 [file2 ...]\n"); return 1; } else{ for(int i =1; i< argc;i++){ int num=-1; int numout=-1; int c; int c1;    FILE* file = fopen(argv[i],"rb"); if(file == NULL){ printf("Cannot Open File\n"); return 1; } else{ while(numout != 0){    numout = fread(&num, sizeof(int), 1, file);    c...

  • URGENT. Need help editing some C code. I have done most of the code it just...

    URGENT. Need help editing some C code. I have done most of the code it just needs the following added: takes an input file name from the command line; opens that file if possible; declares a C struct with three variables; these will have data types that correspond to the data types read from the file (i.e. string, int, float); declares an array of C structs (i.e. the same struct type declared in point c); reads a record from the...

  • How would I change the following C code to implement the following functions: CODE: #include <stdio.h>...

    How would I change the following C code to implement the following functions: CODE: #include <stdio.h> #include <stdlib.h> int main(int argc, char * argv[]) { if (argc != 2) printf("Invalid input!\n"); else { FILE * f = fopen (argv[1], "r"); if (f != NULL) { printf("File opened successfully.\n"); char line[256]; while (fgets(line, sizeof(line), f)) { printf("%s", line); } fclose(f); } else { printf("File cannot be opened!"); } } return 0; } QUESTION: Add a function that uses fscanf like this:...

  • The following C code keeps returning a segmentation fault! Please debug so that it compiles. Also...

    The following C code keeps returning a segmentation fault! Please debug so that it compiles. Also please explain why the seg fault is happening. Thank you #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> // @Name loadMusicFile // @Brief Load the music database // 'size' is the size of the database. char** loadMusicFile(const char* fileName, int size){ FILE *myFile = fopen(fileName,"r"); // Allocate memory for each character-string pointer char** database = malloc(sizeof(char*)*size); unsigned int song=0; for(song =0; song < size;...

  • For the following task, I have written code in C and need help in determining the...

    For the following task, I have written code in C and need help in determining the cause(s) of a segmentation fault which occurs when run. **It prints the message on line 47 "printf("Reading the input file and writing data to output file simultaneously..."); then results in a segmentation fault (core dumped) I am using mobaXterm v11.0 (GNU nano 2.0.9) CSV (comma-separated values) is a popular file format to store tabular kind of data. Each record is in a separate line...

  • C++ HELP I need help with this program. I have done and compiled this program in...

    C++ HELP I need help with this program. I have done and compiled this program in a single file called bill.cpp. It works fine. I am using printf and scanf. Instead of printf and scanf use cin and cout to make the program run. after this please split this program in three files 1. bill.h = contains the class program with methods and variables eg of class file class bill { } 2. bill.cpp = contains the functions from class...

  • C++ HELP I need help with this program. I have done and compiled this program in a single file called bill.cpp. It works fine. But I need to split this program in three files 1. bill.h = contains the...

    C++ HELP I need help with this program. I have done and compiled this program in a single file called bill.cpp. It works fine. But I need to split this program in three files 1. bill.h = contains the class program with methods and variables 2. bill.cpp = contains the functions from class file 3. main.cpp = contains the main program. Please split this program into three files and make the program run. I have posted the code here. #include<iostream>...

  • // READ BEFORE YOU START: // You are given a partially completed program that creates a...

    // READ BEFORE YOU START: // You are given a partially completed program that creates a list of students for a school. // Each student has the corresponding information: name, gender, class, standard, and roll_number. // To begin, you should trace through the given code and understand how it works. // Please read the instructions above each required function and follow the directions carefully. // If you modify any of the given code, the return types, or the parameters, you...

  • Please I need help in C language, I am trying to modify the code per the...

    Please I need help in C language, I am trying to modify the code per the below instructions, but I am getting errors. Can't fgure it out. The attempted code modification and data file is privided below, after the instructions. Thank you. Instructions:                  1.      First, add a function named printMsg that displays a message, a greeting, or an introduction to the program for the user. Add a statement that calls that function from the main function when your program starts....

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT