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.
Related
This program writes, edits and deletes tasks from a txt file. I'm having problems with my add task function (case (1)) in this situation. Here's a snippet of the code:
switch(choice)
{
case '1':
system("cls");
fseek(fp,0,SEEK_END);
another = 'y';
while(another == 'y')
{
printf("\nEnter Task_Name: ");
scanf("%s", &t.Task_Name);
printf("\nEnter Leader: ");
scanf("%s", &t.Leader);
printf("\nEnter L_Email: ");
scanf("%s", &t.L_Email);
printf("\nEnter Member: ");
scanf("%s", &t.Member);
printf("\nEnter Mem_Email: ");
scanf("%s", &t.Mem_Email);
printf("\nEnter Begin_date(dd/mm/yyyy): ");
scanf("%d/%d/%d", &dd,&mm,&yyyy);
printf("\nEnter End_date(dd/mm/yyyy): ");
scanf("%d/%d/%d", &dd,&mm,&yyyy);
fwrite(&t,recsize,1,fp);
printf("\nAdd another task(y/n) ");
fflush(stdin);
another = getche();
}
break;
However, when I attempt to add a date with the above code I get gibberish in return. For example, when I type 11/11/1111 as the start date and 11/11/1111 as the end date, I get 6421994 and 6422005 in return. The same numbers shows up when I input any other date too.
To keep things reproducible I will have to include the entire code;
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<process.h>
#include<dos.h>
int main()
{
FILE * fp, * ft;
char another, choice;
struct task
{
char Task_Name[50], Leader[50], L_Email[50], Member[50], Mem_Email[50], Begin_date[11], End_date[11];
};
struct task t;
int mm, dd, yyyy;
char TaskName[40];
long int recsize;
fp = fopen("task.txt","rb+");
if(fp == NULL)
{
fp = fopen("task.txt","wb+");
if(fp == NULL)
{
printf("Cannot open file");
exit(1);
}
}
recsize = sizeof(t);
while(1)
{
system("cls");
printf("\n\t **** Welcome to Personal System Management ****");
printf("\n\n\n\t\t\tMAIN MENU\n\t\t=====================\n\t\t[1] Add a new Task\n\t\t[2] View all Task\n\t\t[3] Update Task\n\t\t[4] Delete Task\n\t\t[5] Exit Program\n\t\t=================\n\t\t");
printf("Enter choice: ");
choice = getche();
switch(choice)
{
case '1':
system("cls");
fseek(fp,0,SEEK_END);
another = 'y';
while(another == 'y')
{
printf("\nEnter Task_Name: ");
scanf("%s", &t.Task_Name);
printf("\nEnter Leader: ");
scanf("%s", &t.Leader);
printf("\nEnter L_Email: ");
scanf("%s", &t.L_Email);
printf("\nEnter Member: ");
scanf("%s", &t.Member);
printf("\nEnter Mem_Email: ");
scanf("%s", &t.Mem_Email);
printf("\nEnter Begin_date(dd/mm/yyyy): ");
scanf("%d/%d/%d", &dd,&mm,&yyyy);
printf("\nEnter End_date(dd/mm/yyyy): ");
scanf("%d/%d/%d", &dd,&mm,&yyyy);
fwrite(&t,recsize,1,fp);
printf("\nAdd another task(y/n) ");
fflush(stdin);
another = getche();
}
break;
case '2':
system("cls");
rewind(fp);
printf("Task Name|Leader|Leader Email|Member|Member Email|Begin Date|End Date");
while(fread(&t,recsize,1,fp)==1)
{
printf("\n%s %s %s %s %s %d %d",t.Task_Name,t.Leader,t.L_Email,t.Member,t.Mem_Email,t.Begin_date,t.End_date);
}
getch();
break;
case '3':
system("cls");
another = 'y';
while(another == 'y')
{
printf("Enter the task name you want to update: ");
scanf("%s",TaskName);
rewind(fp);
while(fread(&t,recsize,1,fp)==1)
{
if(strcmp(t.Task_Name,TaskName) == 0)
{
printf("Enter new Member name: ");
scanf("%s",&t.Member);
printf("Enter new Member Email: ");
scanf("%s",&t.Mem_Email);
printf("Enter new End Date(dd/mm/yyyy): ");
scanf("%d/%d/%d",&dd,&mm,&yyyy);
fseek(fp,-recsize,SEEK_CUR);
fwrite(&t,recsize,1,fp);
break;
}
}
printf("\nUpdate another task(y/n)");
another = getche();
}
break;
case '4':
system("cls");
another = 'y';
while(another == 'y')
{
printf("Enter the task name you want to delete: ");
scanf("%s",TaskName);
ft = fopen("Temp.dat","wb");
rewind(fp);
while(fread(&t,recsize,1,fp) == 1)
{
if(strcmp(t.Task_Name,TaskName) != 0)
{
fwrite(&t,recsize,1,ft);
}
}
fclose(fp);
fclose(ft);
remove("task.txt");
rename("Temp.dat","task.txt");
fp = fopen("taxt.txt", "rb+");
printf("Delete another task(y/n)");
fflush(stdin);
another = getche();
}
break;
case '5':
fclose(fp);
exit(0);
}
}
return 0;
}
You're never copying the dates into the structure.
printf("\nEnter Begin_date(dd/mm/yyyy): ");
scanf("%d/%d/%d", &dd,&mm,&yyyy);
sprintf(t.Begin_date, "%02d/%02d/%04d", dd, mm, yyyy);
printf("\nEnter End_date(dd/mm/yyyy): ");
scanf("%d/%d/%d", &dd,&mm,&yyyy);
sprintf(t.End_date, "%02d/%02d/%04d", dd, mm, yyyy);
And since these are strings, you need to use %s when printing them, not %d.
printf("\n%s %s %s %s %s %s %s",t.Task_Name,t.Leader,t.L_Email,t.Member,t.Mem_Email,t.Begin_date,t.End_date);
I want to create a menu that shows:
Client details
Property details
Exit
#include <stdio.h>
#include <conio.h>
void main() {
char L,F,H;
float CID,Aoc,Pte,Cost_per_sqft;
int dicnt,age,ch;
printf("Enter the Client ID\n");
scanf("%f", &CID);
printf("Enter the age of client\n");
scanf("%f", &Aoc);
if (age >=60) {
printf("The client is eligible for a discount\n");
} else if (age<60) {
printf("The client is not eligible for a discount\n");
} {
printf("Select Porperty type\nF=Flat\nL=Land\nH=House\n");
scanf("%f", &Pte);
}
printf("Please select the menu option\n");
printf("1.Client ID\n");
printf("2.Property details\n");
printf("3.Exit\n");
scanf("%d", &ch);
switch(ch) {
case 1:
printf("Client ID %f", CID);
printf("Age of client %f", Aoc);
}
}
It's not letting me enter the option to open a menu, also the age else is doesn't work because age => 60 is also showing not eligible for discount. The switch case doesn't work either.
Problem 1 is that you have defined two variables, float Aoc and int age, then attempt to use them interchangeably. Also, the first time age is referenced ( here: if (age >=60) ) it is uninitialized, which contributes to the problems you have described.
Addressing the following will fix the if-else statement for age, and will allow the menu to appear...
Since age is typically a non-float value, i.e. 45 or 50, but never expressed as 45.5.
Suggest replacing, Aoc everywhere it exists with age, (modifying the format specifiers accordingly), and finally, initialize age before use.
Problem 2 is here:
...
{ printf("Select Porperty type\nF=Flat\nL=Land\nH=House\n");
scanf("%f", &Pte);
You are prompting user to input a char value, then attempt to read it in into a float variable Pte. Suggest if desiring to read in as a char, use a " %c" format specifier, and change float Pte to char Pte.
(Note space in format specifier, it is there for this reason.)
{ printf("Select Porperty type\nF=Flat\nL=Land\nH=House\n");
scanf(" %c", &Pte);//note space in front of %c to consume newline
Working code adapted from your original:
void main()
{
char L,F,H;
float CID,Aoc;/*Pte*/
float Cost_per_sqft;
int dicnt,age,ch;
char Pte;
printf("Enter the Client ID\n");
scanf("%f", &CID);
printf("Enter the age of client\n");
scanf("%d", &age);
if (age >=60)
{
printf("The client is eligible for a discount\n");
}
else if (age<60)
{
printf("The client is not eligible for a discount\n");
}
{ printf("Select Porperty type\nF=Flat\nL=Land\nH=House\n");
scanf(" %c", &Pte);
}
printf("Please select the menu option\n");
printf("1.Client ID\n");
printf("2.Property details\n");
printf("3.Exit\n");
scanf("%d", &ch);
switch(ch)
{
case 1:
printf("Client ID %f\n", CID);
printf("Age of client %d", age);
break;
case 2:
;//add content
break;
case 3:
;//add content
break;
}
}
I have to write a program in C for a school project that registers a geriatric client, this is my code:
int position=0, correctData=0, day, month, year, phone, iRS, exercises;
float height, weight;
char confirmation, name[100], address[100], numberToCheck[9];
for(int i=0; Client[i]->name!="NULL";i++){
position++;
if(i==30){
break;
}
}
do{
fflush(stdin);
system("cls");
printf("\n\tINSERT NEW CLIENT");
printf("\nInsert client name: ");
gets(name);
printf("\nInsert client address: ");
gets(address);
printf("\nInsert client birthday(dd/mm/yyyy): ");
scanf("%d/%d/%d", &day,&month,&year);
do{
fflush(stdin);
strcpy(numberToCheck, "");
printf("\nInsert client phone number: ");
gets(numberToCheck); //THIS IS THE LINE ERASING MY ADDRESS VARIABLE
if(isPhone(numberToCheck)==0){
printf("\nNumber not valid");
}
}while(phone(numberToCheck)==0);
phone= validateInput(numberToChek);
do{
fflush(stdin);
strcpy(numberToCheck, "");
printf("\nInsert client tax number: ");
gets(numberToCheck);
if(isIRS(numberToCheck)==0){
printf("\nNumber not valid");
}
}while(isIRS(numberTocheck)==0);
iRS= validateInput(numberToCheck);
printf("\nInsert client height: ");
scanf("%f", &height);
printf("\nInsert client weight: ");
scanf("%f", &weight);
printf("\nInsert the number of exercises made: ");
scanf("%d", &exercise);
fflush(stdin);
system("cls");
printf("Name : %s", name);
printf("\nAddress : %s", address);
printf("\nBirthday : %02d/%02d/%04d", dia, mes, ano);
printf("\nPhone number : %d", telefone);
printf("\IRS : %d", contribuinte);
printf("\nHeight and Weight : %.2fm e %.2fKg", height, weight);
printf("\nNumber of exercises : %d", exercise);
printf("\n\nIs the data correct??(Y/N): ");
scanf("%c", &confirmation);
if(confirmation=='Y' || confirmation=='y'){
strcpy(Client[position]->name, name);
strcpy(Client[position]->address, address);
Client[position]->dayBirth = day;
Client[position]->monthBirth = month;
Client[position]->yearBirth = year;
Client[position]->phone = phone;
Client[position]->iRS = iRS;
Client[position]->height= height;
Client[position]->weight= weight;
Client[position]->exercise = exercise;
correctData = 1;
}
}while(correctData==0);
printf("\nUser registered");
printf("\n\nPress Enter to continue");
system("pause >nul /nobreak");
I receive by reference the array Client[100] so that i can modify its elements.
In the part of the code to check if it's a phone number/iRS number i use a pre-coded submodule to validate it.
The problem I'm having with the code is that it stores the address of the client but when the program receives the numberToCheck to check if it is a phone number the address variable is cleaned, becomes empty and I don't see why.
I appreciate any help and time given to help me solve the problem
I would like to ask why am i getting Run-time Check Failure #2 When i am doing my program?
I'm very new to C programming.
I'm trying to make a Console application that have some option after they key in Y/N,
But whenever i reach the end of all the option i get that error.
Could anyone tell me how i could solve it & what is the proper way of doing this kind of programming?
#define _CRT_SECURE_NO_WARNINGS // To allow Visual studio to use "scanf" function
#include <stdio.h> // Standard Input output . header
#include <Windows.h>
void codername() {
printf("Coder: Rong Yuan\n");
}
void projectname() {
printf("Project name: NPoly Learning\n");
}
void loadcurrentdate() {
SYSTEMTIME str_t;
GetSystemTime(&str_t);
printf("Date: %d . %d . %d \n"
, str_t.wDay, str_t.wMonth, str_t.wYear);
}
int main() {
char option;
int input;
int mincome, fmember, total;
printf("Do you like to see our option? Y/N \n");
scanf("%s", &option);
if (option == 'y' || option == 'Y') {
printf("1. Display Coder Detail\n");
printf("2. Display Project Name\n");
printf("3. Load Current Date\n");
printf("4. Calculator PCI\n");
printf("5. Exit\n");
scanf("%d", &input);
}
else
exit(1);
switch (input) {
case 1:
codername();
printf("Do you like to return to main?");
break;
case 2:
projectname();
break;
case 3:
loadcurrentdate();
break;
case 4:
printf("Enter your house monthly income: ");
scanf("%d", &mincome);
printf("Enter total family member: (INCLUDING YOURSELF) ");
scanf("%d", &fmember);
total = mincome / fmember;
printf("Total PCI: %d / %d = %d \n", mincome, fmember, total);
system("pause");
break;
case 5:
exit(0);
}
}
scanf("%s", &option);
is wrong as option is a char . So replace %s with %c there.%s should be used for strings (array of characters) and %c is the format specifier used for a character.
I'm writing a program that basically just takes a bunch of user input and Outputs it in the form of a check. My problem is that I'm entering 2 sentences and while the second one is fine it completly skips the first one! and the user last name is working but the first name just outputs "z" it is the weirdest thing and my teachers philosophy is figure it out yourself. So can anyone possibly help me?? Here is my code...
#include<stdio.h>
#include<string.h>
int main()
{
char date[8];
int checkNum;
char payeeFirst[10];
char payeeLast[10];
double amount;
char memo[50];
char wordAmount[100];
printf("Please enter the date: ");
scanf("%s", &date);
printf("Please enter the check number: ");
scanf("%d", &checkNum);
printf("Please enter the payee First name: ");
scanf("%s", &payeeFirst);
printf("Please enter payee last name: ");
scanf("%s", &payeeLast);
printf("Please enter amount: ");
scanf("%d", &amount);
printf("Please enter amount in words: ");
fgets (wordAmount, sizeof(wordAmount)-1, stdin);
printf("Please enter memo: ");
fgets (memo, sizeof(memo)-1, stdin);
printf(" \n");
printf("Date: %s .\n", date);
printf("Check Number: %d .\n", checkNum);
printf("Payee: [%s] [%s] .\n", payeeFirst, payeeLast);
printf("Amount: %d .\n", amount);
printf(" Check %d \n", checkNum);
printf(" Date: %s \n", date);
printf("Pay to the\n");
printf("Order of %s %s $%d \n", payeeFirst, payeeLast, amount);
printf("%s", wordAmount);
printf(" \n");
printf(" \n");
printf("Memo: %s \n", memo);
return 0;
}
Your scanf calls all leave the '\n' in the stream (the next scanf will ignore it though).
The first fgets reads an empty string (well ... a string containing a single '\n').
Try reading the numbers with fgets too (to a temporary buffer) and sscanf from the buffer to the correct variable. This way all the '\n' will be accounted for.