Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Using the struct Part definition from the lecture, declare a variable called myP

ID: 3874664 • Letter: U

Question

Using the struct Part definition from the lecture, declare a variable called myPart of that data type. Initialize all field values appropriately (the actual values are your choice).
Write a line of code that doubles the cost field of the myPart variable.
Write two lines of code that get the cost field of the myPart variable from the user using fgets() and sscanf(). You do not have to prompt the user.
Using the struct Part definition from the lecture, declare an array variable called myParts, containing 45 struct Parts.
Write a line of code that doubles the cost field of element #5 of the myParts variable (that is, the element with 5 between the square brackets).
Write two lines of code that get the cost field of element #5 of the myParts variable from the user using fgets() and sscanf(). You do not have to prompt the userstruct Part
{
char partNumber[8];
char name[20];
double cost;
};

Explanation / Answer

/* Text File is:

B1234 Screw 403
C2313 Bolt 534
D6532 Rench 674
E9873 Screw 789
F7777 Bolt 455
G5555 Rench 897
H1234 Hammer 899 */

PROGRAM

#include<stdio.h>

#include<stdlib.h>

//Declare Structure Part

struct Part

{

char partNumber[8];

char name[20];

double cost;

};

FILE *fp; // Declare File Pointer

int main()

{

struct Part myPart={"A123","Bolt",356}; // Initialize Strcuture variable myPart

char p[45]; // Declare array of character variable p

int count=1; // Declare and initialize variable counter

printf(" Cost: %.2lf",myPart.cost); // Display constant cost value in myPart structure variable

fp=fopen("f:\test1.txt","r"); // Open file test1.txt file

fgets(p,45,fp); // read from file fp and store string p

sscanf(p,"%s%s%lf",myPart.partNumber,myPart.name,&myPart.cost); // read file contain structure variables

printf(" Part Number: %s Part Name: %s Part Cost: %.2lf",myPart.partNumber,myPart.name,myPart.cost); // display the first value of a file

while(fgets(p,45,fp)!=NULL) // Declare while loop until end of file

{

sscanf(p,"%s%s%lf",myPart.partNumber,myPart.name,&myPart.cost); // read file contain structure variables until end of file

count++; // counter increment

if(count==5){ // if the record is 5 then print with cost

printf(" Part Number: %s Part Name: %s [Part Cost: %.2lf]",myPart.partNumber,myPart.name,myPart.cost);

break;

}

}

return 0;

}

OUTPUT


Cost: 356.00
Part Number: B1234
Part Name: Screw
Part Cost: 403.00
Part Number: F7777
Part Name: Bolt
[Part Cost: 455.00]