Running into errors trying to read Text File - c

Okay so I'm building a program for work to track volume each day and also split the volume up to how much each different location receives. There are 8 lines in the building. The Text file consists of the day's date, the total volume for the building and the volume for each location (PEN).
Im running into two problems right now both are segregated to my readDay function. where result = fscanf(pi->Date, 40, fp);
issues are
1. Incompatible integer to pointer conversion passing 'int' to parameter of type 'const char*'
2. Incompatible pointer types passing 'char[40]' to parameter of type 'FILE*'(aka 'struct_sFILE*')
Can anyone explain to me what these issues mean. Or if you need any more info in order to help me feel free to ask.
#include <stdio.h>
#include <stdlib.h>
struct Day {
char Date[40];
int Total;
int Pen1;
int Pen2;
int Pen3;
int Pen4;
int Pen5;
int Pen6;
int Pen7;
int Pen8;
};
const char fileName [] = "UPS.txt";
void StartRecord(void);
void printDay(struct Day* pi);
void writeDay(FILE *fp, struct Day *pi);
int readDay(FILE *fp, struct Day *pi);
void readFile(void);
void addDay(void);
int main(int argc, const char * argv[]) {
StartRecord();
int choice;
printf("Enter 1 to read this file or enter 2 to add to it.");
scanf("%d", &choice);
switch (choice) {
case 1: readFile();
break;
default: printf("Not a valid choice\n");
break;
}
getchar();
getchar();
}
void StartRecord(void) {
int count;
int i;
struct Day aDay;
FILE *fp;
fp = fopen(fileName, "w");
if (fp != NULL) {
printf("Enter volume for how many days? ");
scanf("%d", &count);
for (i = 0; i < count; ++i) {
printf("What is today's date? ");
gets(aDay.Date);
printf("What was the total volume for the building for the day?");
scanf("%d", &aDay.Total);
printf("What was the volume for Pen 1? ");
scanf("%d", &aDay.Pen1);
printf("What was the volume for Pen 2? ");
scanf("%d", &aDay.Pen2);
printf("What was the volume for Pen 3? ");
scanf("%d", &aDay.Pen3);
printf("What was the volume for Pen 4? ");
scanf("%d", &aDay.Pen4);
printf("What was the volume for Pen 5? ");
scanf("%d", &aDay.Pen5);
printf("What was the volume for Pen 6? ");
scanf("%d", &aDay.Pen6);
printf("What was the volume for Pen 7? ");
scanf("%d", &aDay.Pen7);
printf("What was the volume for Pen 8? ");
scanf("%d", &aDay.Pen8);
getchar();
writeDay(fp, &aDay);
}
fclose(fp);
}else {
printf("\nError opening file.\n");
}
}
void readFile(void) {
FILE *fp;
struct Day aDay;
fp = fopen(fileName, "r");
if (fp != NULL) {
while (readDay(fp, &aDay)) {
printDay(&aDay);
}
fclose(fp);
} else {
printf("\nError opening File!\n");
}
}
void writeDay(FILE *fp, struct Day *pi) {
fprintf(fp, "%s\n", pi->Date);
fprintf(fp, "%d\n", pi->Total);
fprintf(fp, "%d\n", pi->Pen1);
fprintf(fp, "%d\n", pi->Pen2);
fprintf(fp, "%d\n", pi->Pen3);
fprintf(fp, "%d\n", pi->Pen4);
fprintf(fp, "%d\n", pi->Pen5);
fprintf(fp, "%d\n", pi->Pen6);
fprintf(fp, "%d\n", pi->Pen7);
fprintf(fp, "%d\n", pi->Pen8);
}
int readDay(FILE *fp, struct Day *pi) {
int result;
fgetc(fp); // read the endline
result = fscanf(pi->Date, 40, fp);
if (result == EOF) {
return 0;
}
fscanf(fp, "%d", &pi->Total);
fscanf(fp, "%d", &pi->Pen1);
return 1;
}
void PrintDay(struct Day *pi) {
printf("Records for the day of: %s\n", pi->Date);
printf("Total Volume: %d", pi->Total);
printf("Volume for Pen 1: %d", pi->Pen1);
printf("Volume for Pen 2: %d", pi->Pen2);
printf("Volume for Pen 3: %d", pi->Pen3);
printf("Volume for Pen 4: %d", pi->Pen4);
printf("Volume for Pen 5: %d", pi->Pen5);
printf("Volume for Pen 6: %d", pi->Pen6);
printf("Volume for Pen 7: %d", pi->Pen7);
printf("Volume for Pen 8: %d", pi->Pen8);
printf("\n\n");
}

In one sense, your arguments are the wrong way round. This:
fscanf(pi->Date, 40, fp);
should be:
fscanf(fp, pi->Date, 40);
just like you already have it a few lines further down.
In another sense, what you're trying to do is very strange - you can't read anything into a literal integer. You probably want something more like:
fscanf(fp, "%s", pi->Date);
or possibly:
fscanf(fp, "%39s", pi->Date);
or similar.

Related

Calculating Monthly Money Expenditure From a Txt File in C

How to make monthly and yearly calculations from a txt file in C language? I'm trying to make a C language read and write program, but I'm confused about how to perform operations from it. I'm confused, please help me
This is an example of a txt file that was written
Jaka 2022 12 10 50000
Juki 2020 10 12 750000
Jaka 12 10 10 4000
And here's the code that I made, it's still limited to calculating all total expenses, I can't calculate monthly and yearly.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
void input();
void count();
void monthly_expenditure();
int main()
{
int choice;
do
{
printf("====================================MENU====================================\n");
printf("1. Input Data\n");
printf("2. count expenditure\n");
printf("3. monthly expenditure\n");
printf("4. exit\n");
printf("choice : ");
scanf("%d", &choice);
switch (choice)
{
case 1:
input();
getchar();
break;
case 2:
count();
getchar();
break;
case 3:
monthly_expenditure();
getchar();
break;
case 4:
printf("thank you\n");
getchar();
break;
default:
printf("error\n");
break;
}
} while (choice != 4);
return 0;
}
void input()
{
FILE *fp;
char name[100], year[100], month[100], date[100], money[100];
fp = fopen("data.txt", "a");
printf("Input name : ");
scanf("%s", name);
printf("Input year : ");
scanf("%s", year);
printf("Input month : ");
scanf("%s", month);
printf("Input date : ");
scanf("%s", date);
printf("Input money : ");
scanf("%s", money);
fprintf(fp, "%s %s %s %s %s\n", name, year, month, date, money);
fclose(fp);
}
void count()
{
FILE *fp;
char name[100], year[100], month[100], date[100], money[100];
int total = 0;
fp = fopen("data.txt", "r");
while (fscanf(fp, "%s %s %s %s %s", name, year, month, date, money) != EOF)
{
total += atoi(money);
}
printf("Total expenditure : %d\n", total);
fclose(fp);
}
void monthly_expenditure(){
}
void year_expenditure(){
}
Create one function that passes in the desired year and month.
Use fgets() to read a line of input, then parse. This has far better error handling.
Do not test against EOF, one of the many return values from *scanf() that you do not want. Test against the return value you want.
Use int for year, month, day.
Use a width with %s to avoid buffer overflow.
Recommend a wider type for money.
Illustrative untested code:
// Filter per year. Use 0 for all years, all months
// Return error code.
int count_filter(int year, int month) {
FILE *fp = fopen("data.txt", "r");
if (fp == NULL) {
return 1;
}
long total = 0;
char buf[200];// Some large buffer
while (fgets(buf, sizeof buf, fp)) {
char name[100];
int y, m, d;
long money;
if (sscanf(buf, "%99s %d %d %d %ld",
name, &y, &m, &d, &money) != 5) {
// Incorrect format
fclose(fp);
return 3;
}
if ((year == 0 || year == y) && (month == 0 || month == m)) {
total += money;
}
}
fclose(fp);
printf("Total expenditure: %ld\n", total);
return 0;
}
Now call as needed:
count_filter(0,0); All expenditures
count_filter(2022,12); Just this month
count_filter(2021,0); Last year
count_filter(0,12); All Decembers

Trouble passing a struct to a separate function in C

I'm having trouble passing my struct to a new function. My current code opens a text file, saves the relevant information to the structure and prints the saved information. Now I'm trying to write a function that will ask the user to input a name and for the code to check all name fields in the struct and return inforamtion once found a result. The code works fine until I try pass the struct to the "searchDroneName" function. The main shows that I have saved the relevant information properly and I did the exact same for the "searchDroneName" function. But when I print out the saved information of the struct in the "searchDroneName" function it prints out a bunch of random numbers and weird characters.
I'm sure it's just my lack of understanding of functions and how to pass information but and help is appreciated, thanks.
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define DRONE_COUNT 10
typedef struct{
int drone_number;
char drone_name[20];
int year_manufactured;
double mass;
double top_speed;
double max_distance;
double load_capacity;
} drone_info;
int searchDroneName(int no_of_drones){
drone_info droneinfo[10];
int i, found, numdrones;
char namechoice[20];
numdrones = no_of_drones;
// Test Data
printf("Data:\n\n");
for (i=0; i < numdrones; i++){
printf("ID: %d Name: %s Year: %d Mass: %.2f Top Speed: %.2f Max Distance: %.2f Load Capacity: %.2f\n",
droneinfo[i].drone_number, droneinfo[i].drone_name, droneinfo[i].year_manufactured, droneinfo[i].mass, droneinfo[i].top_speed, droneinfo[i].max_distance, droneinfo[i].load_capacity);
}
printf("Input Drone Name: ");
scanf("%19s", namechoice);
found = 0;
for (i=0; i < numdrones; ++i){
printf("Drone Name: %s\n", droneinfo[i].drone_name);
if (!strcmp(namechoice, droneinfo[i].drone_name)){
printf("FOUND A MATCH");
found = 1;
}
}
if(found == 0){
printf("No Matches Were Found!\n");
}
return 0;
}
int main(void) {
drone_info droneinfo[10];
int choice, droneID, yrman, i, no_of_drones;
float dronemass, dronemaxdist, dronetopspd, droneload;
char dronename[20];
i = 0;
FILE* inputfile = fopen("drone.txt", "r");
if(inputfile == NULL)
{
perror("ERROR! ");
exit(-1);
}
//GAY CODE BELLOW
while(fscanf(inputfile, "%d %19s %d %f %f %f %f", &droneID, dronename, &yrman, &dronemass, &dronetopspd, &dronemaxdist, &droneload)==7){
if(ferror(inputfile)){
perror("An error occurred: ");
}
droneinfo[i].drone_number = droneID;
strcpy(droneinfo[i].drone_name, dronename);
droneinfo[i].year_manufactured = yrman;
droneinfo[i].mass = dronemass;
droneinfo[i].top_speed = dronetopspd;
droneinfo[i].max_distance = dronemaxdist;
droneinfo[i].load_capacity = droneload;
i++;
}
no_of_drones = i;
fclose(inputfile);
printf("Data:\n\n");
for (i=0; i < no_of_drones; i++){
printf("ID: %d Name: %s Year: %d Mass: %.2f Top Speed: %.2f Max Distance: %.2f Load Capacity: %.2f\n",
droneinfo[i].drone_number, droneinfo[i].drone_name, droneinfo[i].year_manufactured, droneinfo[i].mass, droneinfo[i].top_speed, droneinfo[i].max_distance, droneinfo[i].load_capacity);
}
//GAY CODE ABOVE
do{
printf("Please select an option:\n\n");
printf("1. Input/update drone information\n");
printf("2. Search a drone\n");
printf("3. Simulate a drone delivery scenario\n");
printf("4. Display simulation results\n");
printf("5. Save drone information\n");
printf("6. Save all results\n");
printf("7. Exit\n\n");
scanf("%d", &choice);
switch(choice)
{
case 1:
//Input Drone Function
break;
case 2:
//Search Drone function
searchDroneName(no_of_drones);
break;
case 3:
//Simulate Drone function
break;
case 4:
//Display simulation results function
break;
case 5:
//Save drone information function
break;
case 6:
//Save all results function
break;
case 7:
// Exit, Breaks loop
break;
default:
printf("\nInvalid choice! Please enter a number inbetween 1 and 7!\n\n" );
break;
}
} while (choice != 7);
return 0;
}
Change
int searchDroneName(int no_of_drones){
drone_info droneinfo[10];
to
int searchDroneName(drone_info *droneinfo, int no_of_drones){
and
case 2:
//Search Drone function
searchDroneName(no_of_drones);
to
case 2:
//Search Drone function
searchDroneName(droneinfo, no_of_drones);

invalid type argument of '->' editing fields of a structure from a separate function

I'm having problems editing the fields of a structure from a seperate function, I'm trying to edit fields of my drone structure from the update droneinfofunction .basically i get the same error for all the arrows (invalid type argument of '->')
i'm sure this problem stems from my lack of understanding of pointers
any help would be greatly appreciated :)
here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define DRONE_COUNT 10
typedef struct{
//define struct info and variables
int drone_number;
char drone_name[20];
int year_manufactured;
double mass;
double top_speed;
double max_distance;
double load_capacity;
} drone_info;
int updateDroneInfo(drone_info *droneinfo, int no_of_drones) {
int searchID, numdrones, i, drYrMan;
double drMass, drTopSpeed, drMaxDist, drLoadCap;
char drname[20];
numdrones = no_of_drones;
printf("what drone ID would you like to update?: ");
scanf("%d", &searchID);
printf("name: ");
scanf("%s", drname);
printf("year manufactured: ");
scanf("%d", &drYrMan);
printf("mass: ");
scanf("%lf", &drMass);
printf("top speed: ");
scanf("%lf", &drTopSpeed);
printf("max distance: ");
scanf("%lf", &drMaxDist);
printf("load capacity: ");
scanf("%lf", &drLoadCap);
droneinfo[searchID]->drone_number = searchID;
droneinfo[searchID]->drone_name = drname;
droneinfo[searchID]->year_manufactured = drYrMan;
droneinfo[searchID]->mass = drMass;
droneinfo[searchID]->top_speed = drTopSpeed;
droneinfo[searchID]->max_distance = drMaxDist;
droneinfo[searchID]->load_capacity = drLoadCap;
for(i=0; i < numdrones; i++){
}
return 0;
}
//drone search function
int searchDroneName(drone_info *droneinfo, int no_of_drones){
int i, found;
char namechoice[20];
printf("input drone name: ");
scanf("%s", namechoice);
found=0;
scanf("what drone would you like to search %s", namechoice);
for (i=0; i < no_of_drones; i++){
if (!strcmp(namechoice, droneinfo[i].drone_name)) {
printf("found a match\n\nID: %d Name: %s Year: %d Mass: %.2f Top Speed: %.2f Max Distance: %.2f Load Capacity: %.2f\n",
droneinfo[i].drone_number, droneinfo[i].drone_name, droneinfo[i].year_manufactured, droneinfo[i].mass, droneinfo[i].top_speed, droneinfo[i].max_distance, droneinfo[i].load_capacity);
found = 1;
}
}
if(found == 0){
printf("\nNo matches were found!\n");
}
return 0;
//make condition for all
}
int main(void) {
drone_info droneinfo[10];
int choice, droneID, yrman, i, no_of_drones;
double dronemass, dronemaxdist, dronetopspd, droneload;
char dronename[20];
i=0;
//open the drone.txt file where the drone info is stored
FILE* inputfile = fopen("drone.txt", "r");
if(inputfile == NULL)
{
perror("ERROR! ");
exit(-1);
}
//initialise the function that puts the struct in an array
while(fscanf(inputfile, "%d %19s %d %lf %lf %lf %lf", &droneID, dronename, &yrman, &dronemass, &dronetopspd, &dronemaxdist, &droneload)==7){
if(ferror(inputfile)){
perror("An error occurred: ");
}
droneinfo[i].drone_number = droneID;
strcpy(droneinfo[i].drone_name, dronename);
droneinfo[i].year_manufactured = yrman;
droneinfo[i].mass = dronemass;
droneinfo[i].top_speed = dronetopspd;
droneinfo[i].max_distance = dronemaxdist;
droneinfo[i].load_capacity = droneload;
i++;
}
no_of_drones = i;
fclose(inputfile);
//print the dtone info in an array
printf("Data:\n\n");
for (i=0; i < no_of_drones; i++){
printf("ID: %d Name: %s Year: %d Mass: %.2f Top Speed: %.2f Max Distance: %.2f Load Capacity: %.2f\n",
droneinfo[i].drone_number, droneinfo[i].drone_name, droneinfo[i].year_manufactured, droneinfo[i].mass, droneinfo[i].top_speed, droneinfo[i].max_distance, droneinfo[i].load_capacity);
}
do{
//program menu with appropriate menu items
printf("Please select an option:\n\n");
printf("1. Input/update drone information\n");
printf("2. Search a drone\n");
printf("3. Simulate a drone delivery scenario\n");
printf("4. Display simulation results\n");
printf("5. Save drone information\n");
printf("6. Save all results\n");
printf("7. Exit\n\n");
scanf("%d", &choice);
//switch for the 7 available menu cases
switch(choice)
{
case 1:
//input drone function
updateDroneInfo(droneinfo, no_of_drones);
break;
case 2:
//search drone function
searchDroneName(droneinfo, no_of_drones);
break;
case 3:
//simulate drone function
break;
case 4:
//display simulation results
break;
case 5:
//save drone information
break;
case 6:
//save all results function
break;
case 7:
//exit/breaks the loop
break;
default:
printf("Invalid Data Entered! please enter a number between 1 and 7\n\n");
break;
}
} while(choice != 7);
return 0;
}
re
droneinfo[searchID]
has the type drone_info and not drone_info*, so you use . instead of ->.
In statements like this:
droneinfo[searchID]->drone_number = searchID;
the expression droneinfo[searchID] is not a pointer. It has the type drone_info because the pointer droneinfo was already dereferenced by the subscript operator.
You have to write:
droneinfo[searchID].drone_number = searchID;
Also arrays do not have the assignment operator. You need to copy element elements from one array to another.
Instead of this statement:
droneinfo[searchID]->drone_name = drname;
you have to write using the standard string function strcpy:
$include <string.h>
//...
strcpy( droneinfo[searchID].drone_name, drname );

Result is not correct--C Programming

Good day to everyone.
I have a question. How to fix my incorrect result as shown here, on my Point Obtained part, Round 1, the result is not correct? The answer is should be 34 for player 1, 45 for player 2, 50 for player 3.
Also, I also know that fflush(stdin) is not suitable to be implemented in coding. But when I remove fflush(stdin), the fgets is skipping my input. Can anyone suggest me how to fix this?
This is my code:
#include<stdio.h>
int main(void)
{
int round;
int player;
char name1[30];
char name2[30];
char name3[30];
int total1;
int total2;
int total3;
int times;
int point[3];
total1=0;
total2=0;
total3=0;
printf("======League of Legends======\n");
printf("How many round?:");
scanf("%d", &round);
printf("How many player:");
scanf("%d", &player);
fflush(stdin);
printf("Name player 1:");
fgets(name1, 30, stdin);
printf("Name player 2:");
fgets(name2, 30, stdin);
printf("Name player 3:");
fgets(name3, 30, stdin);
for(times=1; times<=round; times++)
{
printf("## Round %d ##\n", times);
printf("Point for player 1(%s):",name1);
scanf("%d", &point[0]);
printf("Point for player 2(%s):", name2);
scanf("%d", &point[1]);
printf("Point for player 3(%s):", name3);
scanf("%d", &point[2]);
total1=total1+point[0];
total2=total2+point[1];
total3=total3+point[2];
}
for(times=1; times<=round; times++)
{
printf("******Point obtained******\n");
printf("## Round %d ##\n", times);
printf("Point for player 1(%s): %d\n", name1, point[0]);
printf("Point for player 2(%s): %d\n", name2, point[1]);
printf("Point for player 3(%s): %d\n", name3, point[2]);
}
printf("++++++TOTAL POINT++++++\n");
printf("Total point player 1(%s):%d\n", name1, total1);
printf("Total point player 2(%s):%d\n", name2, total2);
printf("Total point player 3(%s):%d\n", name3, total3);
return 0;
}
The reason of getting wrong output is that the array point is overwritten by information of later round. You have to store the data separately.
To fix fgets() problem, I will read all lines via fgets() to have them read newline characters.
possible fix:
#include<stdio.h>
#include<stdlib.h>
int readInt(void) {
char buffer[512];
int ret;
fgets(buffer, sizeof(buffer), stdin);
sscanf(buffer, "%d", &ret);
return ret;
}
void readString(char* str, size_t str_size) {
char* p;
fgets(str, str_size, stdin);
for (p=str; *p!='\0' && *p!='\n'; p++);
*p='\0';
}
int main(void)
{
int round;
int player;
char name1[30];
char name2[30];
char name3[30];
int total1;
int total2;
int total3;
int times;
int (*point)[3];
total1=0;
total2=0;
total3=0;
printf("======League of Legends======\n");
printf("How many round?:");
round=readInt();
printf("How many player:");
player=readInt();
printf("Name player 1:");
readString(name1, sizeof(name1));
printf("Name player 2:");
readString(name2, sizeof(name2));
printf("Name player 3:");
readString(name3, sizeof(name3));
point=malloc(sizeof(*point)*round);
for(times=1; times<=round; times++)
{
printf("## Round %d ##\n", times);
printf("Point for player 1(%s):",name1);
scanf("%d", &point[times-1][0]);
printf("Point for player 2(%s):", name2);
scanf("%d", &point[times-1][1]);
printf("Point for player 3(%s):", name3);
scanf("%d", &point[times-1][2]);
total1=total1+point[times-1][0];
total2=total2+point[times-1][1];
total3=total3+point[times-1][2];
}
for(times=1; times<=round; times++)
{
printf("******Point obtained******\n");
printf("## Round %d ##\n", times);
printf("Point for player 1(%s): %d\n", name1, point[times-1][0]);
printf("Point for player 2(%s): %d\n", name2, point[times-1][1]);
printf("Point for player 3(%s): %d\n", name3, point[times-1][2]);
}
free(point);
printf("++++++TOTAL POINT++++++\n");
printf("Total point player 1(%s):%d\n", name1, total1);
printf("Total point player 2(%s):%d\n", name2, total2);
printf("Total point player 3(%s):%d\n", name3, total3);
return 0;
}

C program how to print in table format alignment

The input is retrieve from text file. Which contain information of
product ID
product Name
Product Quantity
product Price
1 RAYBAN 1 450.000000
900 KEYBOARD 100 290.000000
78 MINERALWATER 123 345.000000
2 RAYBAN 2 450.000000
After printing the output through command prompt. It was not align with the 1st item. How to make it align with the title of table. As you can see the input of line 1 and 4 almost the same.
Here is the output.
Here is the full code. With gotoxy function. The display function is on
int displayProduct()
There is a line of code for table titles and also the printf from TXT File.
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <ctype.h>
void gotoxy(int column, int line);
int main();
int addProduct();
int displayProduct(); //prototype
struct product {
int quantity, reorder, i, id;
char name[20];
float price;
};
COORD coord = { 0, 0 };
void gotoxy(int x, int y) {
coord.X = x; coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
int main() {
int choice;
gotoxy(17, 5);
printf("\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2 SYZ INVENTORY PROGRAM \xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2");
gotoxy(17, 20);
printf("\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2");
gotoxy(22, 8);
printf("1. Add Product\n\n");
gotoxy(22, 10);
printf("2. Display Product\n\n");
gotoxy(22, 12);
printf("3. Search Product\n\n");
gotoxy(22, 14);
printf("4. Reorder Level of Product\n\n");
gotoxy(22, 16);
printf("5. Update Product\n\n");
gotoxy(22, 18);
printf("6. Exit\n\n");
gotoxy(22, 22);
printf("Please Enter Your Choice : ");
scanf(" %d", &choice);
switch (choice) {
case 1:
addProduct();
break;
case 2:
displayProduct();
break;
case 3:
searchProduct();
break;
case 4:
reorderProduct();
break;
case 5:
updateProduct();
break;
case 6:
break;
default:
system("cls");
main();
}
return (0);
}
/*MENU CODE ENDS !*/
int addProduct() {
FILE *fp;
int i = 0;
struct product a;
system("cls");
fp = fopen("inventory.txt", "a+t");
char checker;
do {
system("cls");
gotoxy(17, 5);
printf("\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2 SYZ INVENTORY PROGRAM \xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2");
gotoxy(17, 20);
printf("\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2");
gotoxy(22, 8);
printf("Enter product ID : ");
scanf(" %d", &a.id);
gotoxy(22, 10);
printf("Enter product name : ");
scanf(" %s", a.name);
gotoxy(22, 12);
printf("Enter product quantity : ");
scanf(" %d", &a.quantity);
gotoxy(22, 14);
printf("Enter product price : ");
scanf(" %f", &a.price);
gotoxy(22, 17);
fprintf(fp, "%d %s %d %f\n\n", a.id, a.name, a.quantity, a.price); //SAVE TO TXT FILE LINE !
printf("Record saved!\n\n");
fclose(fp);
gotoxy(22, 22);
printf("Do you want to enter new product? Y / N : ");
scanf(" %c", &checker);
checker = toupper(checker);
i++;
system("cls");
} while (checker=='Y');
if (checker == 'N') {
main();
} else {
do {
system("cls");
gotoxy(17, 5);
printf("\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2 SYZ INVENTORY PROGRAM \xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2");
gotoxy(17, 20);
printf("\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2");
gotoxy(18, 8);
printf(">>> Wrong Input! Please Enter Y Or N Only! <<<");
gotoxy(19, 12);
printf("Do You Want To Enter New Product? Y / N : ");
scanf(" %c", &checker);
checker = toupper(checker);
} while (checker != 'Y' && checker != 'N');
if (checker == 'Y'){
addProduct();
}
if (checker == 'N') {
system("cls");
main();
}
}
return(0);
}
/*ADD PRODUCT LINE ENDS !*/
int displayProduct() {
FILE *fp;
struct product a;
char true;
system("cls");
fp = fopen("inventory.txt", "r");
gotoxy(17, 5);
printf("\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2 SYZ INVENTORY PROGRAM \xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2");
gotoxy(5, 6);
printf("======================================================================");
gotoxy(5, 7);
printf("Product ID\t\t Product Name\t\t Quantity\t Unit Price\n"); //TABLE TITLES !
gotoxy(5, 8);
printf("======================================================================");
gotoxy(5,10);
while (fscanf(fp, "%d %s %d %f", &a.id, a.name, &a.quantity, &a.price) == 4) {
printf("%d\t\t\t %s\t\t\t %d\t\t %.2f\n\n", a.id, a.name, a.quantity, a.price); //PRINT FROM TXT FILE TO COMMAND PROMPT.
}
fclose(fp);
printf("\t\t \xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2");
printf("\nPress any key to return to Main Menu.");
getch();
int main();
return (0);
}
Updated one, changes made :
gotoxy(5,10);
while(fscanf(fp, "%d %s %d %f", &a.id, a.name, &a.quantity, &a.price)==4)
{
printf("%-10d\t\t %-12s\t\t %8d\t %8.2f\n\n", a.id, a.name, a.quantity, a.price);
}
fclose(fp);
The code to print the inventory should use the length specifier in printf format like this:
gotoxy(0, 10);
while (fscanf(fp, "%d %s %d %f", &a.id, a.name, &a.quantity, &a.price) == 4) {
printf(" %-10d\t\t %-12s\t\t %8d\t %8.2f\n\n", a.id, a.name, a.quantity, a.price);
}
Some notes regarding the code:
it is very bad style to call main() recursively. Use a loop instead.
write a function that prints the header instead of duplicating the code multiple times.
the statement int main(); at the end of displayProduct() is a local declaration for function main, it does not generate a call.
your menu doesn't go back to the main menu after pressing any key,
there you have to use main(); instead ogf int main();

Resources