C program how to print in table format alignment - c

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();

Related

problem in appending multiple records in a file

I am having problem with appending more records to this file. It allows me add just one record but I cannot add more than one record. And cannot figure out what is going wrong with it?
void new_customer()
{
char ch;
int flag=0;
FILE *fp;
fp=fopen("DataFile.txt", "a+");
printf("Enter today's date (dd/mm/yyyy) : ");
scanf(" %d/%d/%d", &add.deposit.day, &add.deposit.month, &add.deposit.year);
printf("Enter Account Number : ");
fflush(stdin);
scanf("%ld", &check.account_number);
while(fscanf(fp, "%ld %s %s %s %s %s %d %d/%d/%d %d %d/%d/%d %c", &add.account_number, add.customer_name, add.father_name, add.address, add.Nationality, &add.p_number, &add.age, &add.dob.day, &add.dob.month, &add.dob.year, &add.amount, &add.deposit.day, &add.deposit.month, &add.deposit.year, &add.account_type)!=EOF)
{
if(check.account_number==add.account_number)
{
printf("Account number already taken. Please contact administrator.\nPress enter to continue.");
getch();
system("cls");
main();
}
}
add.account_number=check.account_number;
printf("Enter name : ");
fflush(stdin);
gets(add.customer_name);
printf("Enter Father's name : ");
fflush(stdin);
gets(add.father_name);
printf("Enter your age : ");
fflush(stdin);
scanf("%d", &add.age);
printf("Enter Date of birth (dd/mm/yyyy) : ");
scanf("%d/%d/%d", &add.dob.day, &add.dob.month, &add.dob.year);
printf("Enter Phone Number : ");
fflush(stdin);
gets(add.p_number);
printf("Enter Nationality : ");
fflush(stdin);
gets(add.Nationality);
printf("Enter Address : ");
fflush(stdin);
gets(add.address);
printf("Enter Account Type:\nPress S for Savings, \nPress C for Current, \nF for Fixed : ");
fflush(stdin);
scanf("%c",&add.account_type);
while(flag!=1)
{
if (add.account_type=='S'|| add.account_type=='s'||add.account_type=='C'||add.account_type=='c'||add.account_type=='F'||add.account_type=='f')
{
flag=1;
}
else
{
printf("\nWrong Input. Input Again : ");
fflush(stdin);
scanf("%c", &add.account_type);
flag=0;
}
}
printf("Deposit Amount : ");
fflush(stdin);
scanf("%d", &add.amount);
fprintf(fp, "%ld %s %s %s %s %s %d %d/%d/%d %d %d/%d/%d %c\n", add.account_number, add.customer_name, add.father_name, add.address, add.Nationality, add.p_number, add.age, add.dob.day, add.dob.month, add.dob.year, add.amount, add.deposit.day, add.deposit.month, add.deposit.year, add.account_type);
printf("\nAccount Created Successfully!!\n");
fclose(fp);
while(1)
{
printf("Return to Main Menu? Y/N : ");
fflush(stdin);
scanf("%c", &ch);
if(ch=='Y' || ch=='y')
{
system("cls");
main();
}
else if(ch=='N' || ch=='n')
{
exit(0);
}
else
{
printf("\nWrong input. Try Again!\n");
}
}
}
This is just a function to a big program. I am attaching just the part which includes file handling. If you want I can attach more code.
Here I am adding the main driver code
#include<windows.h>
#include<stdio.h>
#include<stdlib.h>
#include "E:\Projects\C Language\Bank-Management-System\File Containing Functions.c"
int menu(void);
int gotoxy(int x, int y)
{
COORD c;
c.X=x;
c.Y=y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), c);
}
int menu()
{
int i, a;
gotoxy(40,0);
printf("BANK MANAGEMENT SYSTEM\n");
gotoxy(43, 3);
printf(":: MAIN MENU ::\n");
gotoxy(40, 5);
printf("[1] Create a new account");
gotoxy(40, 6);
printf("[2] Update information of existing account");
gotoxy(40, 7);
printf("[3] Transactions");
gotoxy(40, 8);
printf("[4] Check details of existing account");
gotoxy(40, 9);
printf("[5] Remove existing account");
gotoxy(40, 10);
printf("[6] View Customer List");
gotoxy(40, 11);
printf("[7] Exit\n");
gotoxy(40, 15);
printf("Enter your choice : ");
scanf("%d", &a);
return a;
}
int main()
{
int choice;
choice=menu();
switch(choice)
{
case 1:
{
system("cls");
new_customer();
break;
}
case 3:
{
system("cls");
transaction();
break;
}
case 7 :
{
system("cls");
printf("Thank You for using our services!!");
exit(0);
}
default:
{
printf("Wrong Input!!\n");
getch();
system("cls");
menu();
}
}
getch();
return 0;
}
Link to see input : https://pasteboard.co/Jt3xWrP.jpg
Here is the file after first input : https://pasteboard.co/Jt3yYA9.jpg
Another input :https://pasteboard.co/Jt3yHSC.jpg (this is where it gets stuck forever and doesn't let me add another record)
Text stored inside file :
123 John Papa John 15, Yemen Road, Yemen USA 12345678 22 11/2/0 2000 27/9/2020 S
So to start with the file holds:
123 John Papa John 15, Yemen Road, Yemen USA 12345678 22 11/2/0 2000 27/9/2020 S
And you try to scan it with
fscanf(fp, "%ld %s %s %s %s %s %d %d/%d/%d %d %d/%d/%d %c"
That is:
1 number
5 strings
1 number
...
As you can see, the file doesn't match that.
123 John Papa John 15, Yemen Road, Yemen USA 12345678 22 11/2/0 2000 27/9/2020 S
^^^ ^^^ ^^^ ^^^ ^^^ ^^^ ^^^
ok ok ok ok ok ok Not ok, so stop here
The next fscanf will not match anything (it expects a number but the file has "Road") so nothing is read.
In other words, you are stuck in the while forever.
I'll recommend reading the file in a line by line manner using fgets.
Then you can (in principle) use sscanf afterwards. But notice that %s reads a single word and your code allow multiple words for a single entry! In other words - your file can't be parsed using %s.
So consider another file format. For instance, you could use 1 line for each item in a record. That will make parsing much easier.

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 );

C Program GOTOXY on second screen

The first screen, gotoxy code is working. But in second screen. Nothing happens, like, it does not read the gotoxy code at all. Please enlighten me about the problem.
Here is the 1st screen :
Here is the 2nd screen :
Here is the code. I would love to learn more about gotoxy.
Thank you in advance.
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <ctype.h>
void gotoxy( int column, int line );
int main();
int addProduct();
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,18);
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,20);
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;
default : printf("Wrong input. Please try again.");
system("cls");
main();
}
return (0);
}
int addProduct()
{
FILE * fp;
int i=0;
struct product a;
system("cls");
char checker;
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,18);
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");
do
{
fp = fopen("inventory.txt","a+t");
system("cls");
printf("Enter product ID : ");
scanf(" %d", &a.id);
printf("Enter product name : ");
scanf(" %s", a.name);
printf("Enter product quantity : ");
scanf(" %d", &a.quantity);
printf("Enter product price : ");
scanf(" %f", &a.price);
fprintf(fp, "%d %s %d %f\n\n", a.id, a.name, a.quantity, a.price);
printf("Record saved!\n\n");
fclose(fp);
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{
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);
}

how to repeat a c program from the beginning and clean the screen and 1st input values?

i m new in programing.
i've written a simple program.
i want to repeat the program again and again and it can only exit when user wants to exit.
here is my program
#include<stdio.h>
#include<conio.h>
main()
{
char ch;
int num1, num2, a, m, s, choice;
float d;
printf("\nEnter The First Number: ");
scanf("%d", &num1);
printf("\nEnter The Second Number: ");
scanf("%d", &num2);
a=num1+num2;
m=num1*num2;
s=num1-num2;
d=(float)(num1/num2);
printf("\nEnter Your Choice \nFor Addition Type A \nFor Multipication Type M \nFor Division Type D \nFor Substraction Type S : ");
scanf(" %c", &ch);
switch(ch)
{
case 'A': printf("\nThe Addition Of The Number Is= %d", a);
break;
case 'M': printf("\nThe Multipication Of The Numbers Is= %d", m);
break;
case 'S': printf("\nThe Substraction Of THe Numbers Is= %d", s);
break;
case 'D': printf("\nThe Division Of The Two Numbers Is= %f", d);
break;
default : printf("\nInvalid Entry");
break;
}
printf("\nPress Any Key To Exit");
getch();
return 0;
}
and here is the output
"Enter The First Number: 10
Enter The Second Number: 10
Enter Your Choice
For Addition Type A
For Multipication Type M
For Division Type D
For Substraction Type S : A
The Addition Of The Number Is= 20
Press Any Key To Exit"
I want a line before the line Press Any Key To Exit
"If You Want To Calculate Again Press Y
or
Press Any Key To Exit"
when press Y then the program should start from the beginning.
How can i do this???
wrap the code inside a do{} while() ?
char answer;
do{
printf("\nEnter The First Number: ");
scanf("%d", &num1);
printf("\nEnter The Second Number: ");
scanf("%d", &num2);
a=num1+num2;
m=num1*num2;
s=num1-num2;
d=(float)(num1/num2);
printf("\nEnter Your Choice \nFor Addition Type A \nFor Multipication Type M \nFor Division Type D \nFor Substraction Type S : ");
scanf(" %c", &ch);
switch(ch)
{
case 'A': printf("\nThe Addition Of The Number Is= %d", a);
break;
case 'M': printf("\nThe Multipication Of The Numbers Is= %d", m);
break;
case 'S': printf("\nThe Substraction Of THe Numbers Is= %d", s);
break;
case 'D': printf("\nThe Division Of The Two Numbers Is= %f", d);
break;
default : printf("\nInvalid Entry");
break;
}
printf("\nPress Y to continue. Press any Key To Exit");
scanf(" %c",&answer); // dont forget type &
}
while(answer == 'y' || answer == 'Y');
Declare a variable, let's say answer, which will store the user answer when you ask for "Press Y to continue. Press any Key To Exit". Check to see what value has that variable. If is 'y' or 'Y', the loop will repeat. If the user pressed other key, the loop is over.
You can also use recursion, which is often used in more functional oriented programming languages.
Pseudo-code:
myfunction = do
...
b <- somethingtodo
...
if b
then myfunction
else return ()
Relative to Jens's solution, it would look like:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main (void)
{
char choice;
int num1, num2, cont;
printf("Enter the first number: ");
scanf("%d", &num1);
getchar ();
printf("Enter the second number: ");
scanf("%d", &num2);
getchar ();
printf("A - addition\n");
printf("S - subtraction\n");
printf("M - multiplication\n");
printf("D - division\n");
printf("[ASMD]? ");
choice = (char)toupper(getchar());
getchar ();
printf("\n");
switch(choice)
{
case 'A':
printf("%d + %d = %d", num1, num2, num1 + num2);
break;
case 'S':
printf("%d - %d = %d", num1, num2, num1 - num2);
break;
case 'M':
printf("%d * %d = %d", num1, num2, num1 * num2);
break;
case 'D':
if (num2 == 0)
fprintf(stderr, "The divisor can not be zero");
else
{
printf("%d / %d = %f", num1, num2, (double)num1 / num2);
}
break;
default :
fprintf(stderr, "Invalid entry");
break;
}
printf("\n");
for (;;)
{
printf("Continue [YN]? ");
cont = toupper(getchar());
getchar ();
if (cont == 'Y')
return main(); // the difference.
else if (cont == 'N')
return EXIT_SUCCESS;
}
}
I would move the calculation stuff in it's own function and then use while() in main.
I have tried to fix other problems as well (this solution only uses standard C functions).
#include <stdio.h> // puts, printf, fprintf, scanf, getchar, stderr, EOF
#include <stdlib.h> // exit, EXIT_SUCCESS, EXIT_FAILURE
#include <ctype.h> // toupper
char fail_on_eof (int c)
{
if (c == EOF)
exit (EXIT_FAILURE);
// In case of fail_on_eof (scanf (...)) the return value of this this
// function is not useful
// scanf () returns the number of chars read or EOF
// getchar () returns a char or EOF
return (char) c;
}
void skip_to_next_line (void)
{
char c;
do
{
c = fail_on_eof (getchar ());
} while (c != '\n');
}
char read_upcase_char_line (char* prompt)
{
char c;
printf ("%s ", prompt);
c = fail_on_eof (toupper (getchar ()));
skip_to_next_line ();
return c;
}
int read_num_line (char* prompt)
{
int num;
printf ("%s ", prompt);
fail_on_eof (scanf ("%d", &num));
skip_to_next_line ();
return num;
}
int calculate (void)
{
char choice;
int num1, num2, cont;
num1 = read_num_line ("Enter the first number:");
num2 = read_num_line ("Enter the second number:");
puts("A - addition");
puts("S - subtraction");
puts("M - multiplication");
puts("D - division");
choice = read_upcase_char_line ("[ASMD]?");
puts("");
switch(choice)
{
case 'A':
printf("%d + %d = %d", num1, num2, num1 + num2);
break;
case 'S':
printf("%d - %d = %d", num1, num2, num1 - num2);
break;
case 'M':
printf("%d * %d = %d", num1, num2, num1 * num2);
break;
case 'D':
if (num2 == 0)
// Better use stderr for error messages
fprintf(stderr, "The divisor can not be zero");
else
{
printf("%d / %d = %f", num1, num2, (double)num1 / num2);
}
break;
default :
// Better use stderr for error messages
fprintf(stderr, "Invalid entry");
break;
}
printf("\n");
for (;;)
{
cont = read_upcase_char_line ("Continue [YN]?");
if (cont == 'Y')
return -1;
else if (cont == 'N')
return 0;
}
}
int main(void)
{
while (calculate ());
return EXIT_SUCCESS; // Use this constant to avoid platform specific issues with the return code
}

Resources