How to accept space in string in C in the given code - c

Sorry about the previous code, I did not correctly interpreted the situation.
What's happening is the string is being stored with spaces but when i am trying to read it afterwards, The output flickers continuously (its like its reading it over and over again and printing it infinitely on itself.)
The records are stored in a file named record.dat
I am inserting image showing file contents stored after I input a new record in the file (Everything gets stored correctly here)
![These are the contents of record.dat right after i insert the new record]--> the image --> http://i.stack.imgur.com/YxGEd.png
and now when I try to look the details of this record on my application I get this.
![Output showing the record details but not entirely correct as " Finch" is missing] -- >> the image -- >> http://i.stack.imgur.com/zgmGY.png
and after this if i close the application and then start it again and try to read the previous data it shows this:
![This output is also flickering like before but now even the data is gone]-->> the image -->> http:// i.stack.imgur.com/ 4q0qb.png
(and just in case you are wondering -- the data is still there in the record.dat file -- all of it which i entered when i prevously created the record.)
I hope the problem is more clear now.....
void see(void)
{
FILE *ptr;
int test=0,rate;
int choice;
float time;
float intrst;
char c;
ptr=fopen("record.dat","r");
printf("Do you want to check by\n1.Account no\n2.Name\nEnter your choice:");
//Selection Choice with Validation
int once = 0;
do
{
if(once!=0)
{
printf("\nThe choice is invalid.\nEnter 1 for account number and 2 for name");
}
once = once+1;
} while ((scanf("%d%c", &choice, &c)!=2 || c!='\n') && clean_stdin());
if (choice==1)
{
//Account Number with Validation
once = 0;
do
{
if(once!=0)
{
printf("\nThe above account number is invalid.\nEnter an account number (numeric value only):");
}
else
{
printf("\nEnter an account number:");
}
once = once+1;
} while ((scanf("%d%c", &check.acc_no, &c)!=2 || c!='\n') && clean_stdin());
while (fscanf(ptr,"%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d",&add.acc_no,add.name,&add.dob.month,&add.dob.day,&add.dob.year,&add.age,add.address,add.citizenship,&add.phone,add.acc_type,&add.amt,&add.deposit.month,&add.deposit.day,&add.deposit.year)!=EOF)
{
if(add.acc_no==check.acc_no)
{ system("cls");
test=1;
printf("\nAccount NO.:%d\nName:%s \nDOB:%d/%d/%d \nAge:%d \nAddress:%s \nCitizenship No:%s \nPhone number:%.0lf \nType Of Account:%s \nAmount deposited:$ %.2f \nDate Of Deposit:%d/%d/%d\n\n",add.acc_no,add.name,add.dob.month,add.dob.day,add.dob.year,add.age,add.address,add.citizenship,add.phone,
add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.deposit.year);
if(strcmpi(add.acc_type,"fixed1")==0)
{
time=1.0;
rate=9;
intrst=interest(time,add.amt,rate);
printf("\n\nYou will get $%.2f as interest on %d/%d/%d",intrst,add.deposit.month,add.deposit.day,add.deposit.year+1);
}
else if(strcmpi(add.acc_type,"fixed2")==0)
{
time=2.0;
rate=11;
intrst=interest(time,add.amt,rate);
printf("\n\nYou will get $.%.2f as interest on %d/%d/%d",intrst,add.deposit.month,add.deposit.day,add.deposit.year+2);
}
else if(strcmpi(add.acc_type,"fixed3")==0)
{
time=3.0;
rate=13;
intrst=interest(time,add.amt,rate);
printf("\n\nYou will get $.%.2f as interest on %d/%d/%d",intrst,add.deposit.month,add.deposit.day,add.deposit.year+3);
}
else if(strcmpi(add.acc_type,"saving")==0)
{
time=(1.0/12.0);
rate=8;
intrst=interest(time,add.amt,rate);
printf("\n\nYou will get $.%.2f as interest on %d of every month",intrst,add.deposit.day);
}
else if(strcmpi(add.acc_type,"current")==0)
{
printf("\n\nYou will get no interest\a\a");
}
}
}
}
else if (choice==2)
{
printf("Enter the name:");
scanf("%s",&check.name);
while (fscanf(ptr,"%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d",&add.acc_no,add.name,&add.dob.month,&add.dob.day,&add.dob.year,&add.age,add.address,add.citizenship,&add.phone,add.acc_type,&add.amt,&add.deposit.month,&add.deposit.day,&add.deposit.year)!=EOF)
{
if(strcmpi(add.name,check.name)==0)
{ system("cls");
test=1;
printf("\nAccount No.:%d\nName:%s \nDOB:%d/%d/%d \nAge:%d \nAddress:%s \nCitizenship No:%s \nPhone number:%.0lf \nType Of Account:%s \nAmount deposited:$%.2f \nDate Of Deposit:%d/%d/%d\n\n",add.acc_no,add.name,add.dob.month,add.dob.day,add.dob.year,add.age,add.address,add.citizenship,add.phone,
add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.deposit.year);
if(strcmpi(add.acc_type,"fixed1")==0)
{
time=1.0;
rate=9;
intrst=interest(time,add.amt,rate);
printf("\n\nYou will get $.%.2f as interest on %d/%d/%d",intrst,add.deposit.month,add.deposit.day,add.deposit.year+1);
}
else if(strcmpi(add.acc_type,"fixed2")==0)
{
time=2.0;
rate=11;
intrst=interest(time,add.amt,rate);
printf("\n\nYou will get $.%.2f as interest on %d/%d/%d",intrst,add.deposit.month,add.deposit.day,add.deposit.year+2);
}
else if(strcmpi(add.acc_type,"fixed3")==0)
{
time=3.0;
rate=13;
intrst=interest(time,add.amt,rate);
printf("\n\nYou will get $.%.2f as interest on %d/%d/%d",intrst,add.deposit.month,add.deposit.day,add.deposit.year+3);
}
else if(strcmpi(add.acc_type,"saving")==0)
{
time=(1.0/12.0);
rate=8;
intrst=interest(time,add.amt,rate);
printf("\n\nYou will get $.%.2f as interest on %d of every month",intrst,add.deposit.day);
}
else if(strcmpi(add.acc_type,"current")==0)
{
printf("\n\nYou will get no interest\a\a");
}
}
}
}
fclose(ptr);
if(test!=1)
{ system("cls");
printf("\nRecord not found!!\a\a\a");
see_invalid:
printf("\nEnter 0 to try again,1 to return to main menu and 2 to exit:");
scanf("%d",&main_exit);
system("cls");
if (main_exit==1)
menu();
else if (main_exit==2)
close();
else if(main_exit==0)
see();
else
{
system("cls");
printf("\nInvalid!\a");
goto see_invalid;}
}
else
{printf("\nEnter 1 to go to the main menu and 0 to exit:");
scanf("%d",&main_exit);}
if (main_exit==1)
{
system("cls");
menu();
}
else
{
system("cls");
close();
}
}

The recommended solution is not to use scanf since scanf is also vulnerable to buffer overflows. In any case, you are not actually doing any formatting with the scanf call. You can use fgets to read the input into a string and specify the maximum number of characters that you allow. Use something like the following:
printf("\nEnter the name: ");
fgets(add.name, MAX_NAME_SZ, stdin);

You can use the %[^...] format specifier to read spaces into a string. Here's an example program that hopefully gives you something to work from.
#include <stdio.h>
int main()
{
char const* line = "This is a string, 10";
char text[50];
int number;
// Read up to 49 characters not including ',' to text.
sscanf(line, "%49[^,], %d", text, &number);
printf("%s, %d\n", text, number);
return 0;
}
Output:
This is a string, 10

I think you should provide an example of a failing situation or at least clean up the code and only give us the buggy part.
I see a lot of printf use without \n at the end which I know can be a problem (which may aswell be completely out of the subject here).
Since I've never used scanf I can't tell where your error is but maybe if you reduced your code to the acquisition of the user's input (-> the scanf part) then an attempt to display it (-> the part where your string gets truncated as it meets the first space) we could easily help you fix that problem faster and would be nicer to read.

Related

Compilation Error in C program in CodeBlocks

I intend to use a C program which would povide Banking Services including
Adding a Bank Account
Update Information of existing account
Viewing a Customer's past transactions
Viewing details of an account
Deleting a Customer's Account
Viewing existing accounts
For this I have made functions to be called at appropriate places namely(in order of service listed above),
menu() – This function displays the menu or welcome screen to perform different banking activities mentioned below.
new_acc() – This function creates a new customer account. It asks for some personal and banking details of the customer such as name, date of birth, citizenship number, address and phone number. You can enter the amount to deposit and choose one type of deposit account – saving, current, fixed for 1 year, fixed for 2 years or fixed for 3 years.
view list() – With this function, you can view the customer’s banking information such as account number, name, address and phone number provided while creating the account.
edit() – This function has been used for changing the address and phone number of a particular customer account.
transact() – With this function, you can deposit and withdraw money to and from a particular customer account.
erase() – This function is for deleting a customer account.
see() – This function shows account number, name, date of birth, citizenship number, age, address, phone number, type of account, amount deposited and date of deposit. It also displays the amount of interest corresponding to a particular account type.
File handling has been used for almost all functions. File has been used to store data related to new account, transaction, editing of account information and viewing of account information. I haven’t used file handling for the menu, interest calculation and password.
NOTE: Password to access the program is g5rox
#include<stdio.h>
#include<stdlib.h>
#include<windows.h>
int main_exit;
void menu();
struct date
{
int month,day,year;
};
struct {
char name;
int acc_no,age;
char address[60];
char aadhar[12];
double phone[10];
char acc_type[10];
float amt;
struct date dob;
struct date deposit;
struct date withdraw;
}add,upd,check,rem,transaction;
float interest(float t,float amount,int rate)
{
float SI;
SI=(rate*t*amount)/100.0;
return (SI);
}
void fordelay(int j)
{ int i,k;
for(i=0;i<j;i++)
k=i;
}
void new_acc()
{
int choice;
FILE *ptr;
ptr=fopen("record.dat","a+");
account_no:
system("cls");
printf("\t\t\t\xB2\xB2\xB2\xB2 ADD RECORD \xB2\xB2\xB2\xB2");
printf("\n\n\nEnter today's date(mm/dd/yyyy):");
scanf("%d/%d/%d",&add.deposit.month,&add.deposit.day,&add.deposit.year);
printf("\nEnter your #Account number:");
scanf("%d",&check.acc_no);
while(fscanf(ptr,"%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d\n",add.acc_no,add.name,add.dob.month,add.dob.day,add.dob.year,add.age,add.address,add.aadhar,add.phone,add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.deposit.year)!=EOF)
{
if (check.acc_no==add.acc_no)
{printf("Sorry, Account no. already in use!");
fordelay(1000000000);
goto account_no;
}
}
add.acc_no=check.acc_no;
printf("\nEnter your #Name:");
scanf("%s",&add.name);
printf("\nEnter the #DateOfBirth(mm/dd/yyyy):");
scanf("%d/%d/%d",&add.dob.month,&add.dob.day,&add.dob.year);
printf("\nEnter the #Age:");
scanf("%d",&add.age);
printf("\nEnter the #Address:");
scanf("%s",&add.address);
printf("\nEnter your #Aadhar number:");
scanf("%s",&add.aadhar[12]);
printf("\nEnter the #Mobile number: ");
scanf("%lf",&add.phone);
printf("\nEnter the #Amount to deposit:Rs");
scanf("%f",&add.amt);
printf("\nType of account:\n\t#Saving\n\t#Current\n\t#Fixed1(for 1 year)\n\t#Fixed2(for 2 years)\n\t#Fixed3(for 3 years)\n\n\tEnter your choice:");
scanf("%s",&add.acc_type);
//
fprintf(ptr,"%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d\n",add.acc_no,add.name,add.dob.month,add.dob.day,add.dob.year,add.age,add.address,add.aadhar,add.phone,add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.deposit.year);
fclose(ptr);
printf("\nKudos! Account created successfully!");
add_invalid:
printf("\n\n\n\t\tEnter 1 to go to the main menu and 0 to exit:");
scanf("%d",&main_exit);
system("cls");
if (main_exit==1)
menu();
else if(main_exit==0)
close();
else
{
printf("\nInvalid!\a");
goto add_invalid;
}
}
void view_list()
{
FILE *view;
view=fopen("record.dat","r");
int test=0;
system("cls");
printf("\nACC. NO.\tNAME\t\t\tADDRESS\t\t\tPHONE\n");
while(fscanf(view,"%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d",add.acc_no,add.name,add.dob.month,add.dob.day,add.dob.year,add.age,add.address,add.aadhar,add.phone,add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.deposit.year)!=EOF)
{
printf("\n%6d\t %10s\t\t\t%10s\t\t%.0lf",add.acc_no,add.name,add.address,add.phone);
test++;
}
fclose(view);
if (test==0)
{ system("cls");
printf("\nNO RECORDS!!\n");}
view_list_invalid:
printf("\n\nEnter 1 to go to the main menu and 0 to exit:");
scanf("%d",&main_exit);
system("cls");
if (main_exit==1)
menu();
else if(main_exit==0)
close();
else
{
printf("\nInvalid!\a");
goto view_list_invalid;
}
}
void edit(void)
{
int choice,test=0;
FILE *old,*newrec;
old=fopen("record.dat","r");
newrec=fopen("new.dat","w");
printf("\nEnter the account no. of the customer whose info you want to change:");
scanf("%d",&upd.acc_no);
while(fscanf(old,"%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d",add.acc_no,add.name,&add.dob.month,add.dob.day,add.dob.year,add.age,add.address,add.aadhar,add.phone,add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.deposit.year)!=EOF)
{
if (add.acc_no==upd.acc_no)
{ test=1;
printf("\nWhat information do you want to change?\n1.Address\n2.Phone\n\nEnter your choice(1 for address and 2 for phone):");
scanf("%d",&choice);
system("cls");
if(choice==1)
{printf("Enter the new address:");
scanf("%s",upd.address);
fprintf(newrec,"%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d\n",add.acc_no,add.name,add.dob.month,add.dob.day,add.dob.year,add.age,upd.address,add.aadhar,add.phone,add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.deposit.year);
system("cls");
printf("Changes saved!");
}
else if(choice==2)
{
printf("Enter the new phone number:");
scanf("%lf",&upd.phone);
fprintf(newrec,"%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d\n",add.acc_no,add.name,add.dob.month,add.dob.day,add.dob.year,add.age,add.address,add.aadhar,upd.phone,add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.deposit.year);
system("cls");
printf("Changes saved!");
}
}
else
fprintf(newrec,"%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d\n",add.acc_no,add.name,add.dob.month,add.dob.day,add.dob.year,add.age,add.address,add.aadhar,add.phone,add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.deposit.year);
}
fclose(old);
fclose(newrec);
remove("record.dat");
rename("new.dat","record.dat");
if(test!=1)
{ system("cls");
printf("\nSorry, Record not found!!\a\a\a");
edit_invalid:
printf("\nEnter 0 to try again,1 to return to main menu and 2 to exit:");
scanf("%d",&main_exit);
system("cls");
if (main_exit==1)
menu();
else if (main_exit==2)
close();
else if(main_exit==0)
edit();
else
{printf("\nInvalid!\a");
goto edit_invalid;}
}
else
{printf("\n\n\nEnter 1 to go to the main menu and 0 to exit:");
scanf("%d",&main_exit);
system("cls");
if (main_exit==1)
menu();
else
close();
}
}
void transact(void)
{ int choice,test=0;
FILE *old,*newrec;
old=fopen("record.dat","r");
newrec=fopen("new.dat","w");
printf("Enter the account no. :");
scanf("%d",&transaction.acc_no);
while (fscanf(old,"%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d",add.acc_no,add.name,add.dob.month,add.dob.day,add.dob.year,add.age,add.address,add.aadhar,add.phone,add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.deposit.year)!=EOF)
{
if(add.acc_no==transaction.acc_no)
{ test=1;
if(strcmpi(add.acc_type,"fixed1")==0||strcmpi(add.acc_type,"fixed2")==0||strcmpi(add.acc_type,"fixed3")==0)
{
printf("\a\a\a\n\nSorry, but YOU CANNOT DEPOSIT OR WITHDRAW CASH IN FIXED ACCOUNTS!!!!!");
fordelay(1000000000);
system("cls");
menu();
}
printf("\n\nDo you want to\n1.Deposit\n2.Withdraw?\n\nEnter your choice(1 for deposit and 2 for withdraw):");
scanf("%d",&choice);
if (choice==1)
{
printf("Enter the amount you want to deposit:Rs ");
scanf("%f",&transaction.amt);
add.amt+=transaction.amt;
fprintf(newrec,"%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d\n",add.acc_no,add.name,add.dob.month,add.dob.day,add.dob.year,add.age,add.address,add.aadhar,add.phone,add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.deposit.year);
printf("\n\nKudos! Deposited successfully!");
}
else
{
printf("Enter the amount you want to withdraw:Rs ");
scanf("%f",&transaction.amt);
add.amt-=transaction.amt;
fprintf(newrec,"%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d\n",add.acc_no,add.name,add.dob.month,add.dob.day,add.dob.year,add.age,add.address,add.aadhar,add.phone,add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.deposit.year);
printf("\n\nKudos! Withdrawn successfully!");
}
}
else
{
fprintf(newrec,"%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d\n",add.acc_no,add.name,add.dob.month,add.dob.day,add.dob.year,add.age,add.address,add.aadhar,add.phone,add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.deposit.year);
}
}
fclose(old);
fclose(newrec);
remove("record.dat");
rename("new.dat","record.dat");
if(test!=1)
{
printf("\n\nSorry, Record not found!!");
transact_invalid:
printf("\n\n\nEnter 0 to try again,1 to return to main menu and 2 to exit:");
scanf("%d",&main_exit);
system("cls");
if (main_exit==0)
transact();
else if (main_exit==1)
menu();
else if (main_exit==2)
close();
else
{
printf("\nInvalid!");
goto transact_invalid;
}
}
else
{
printf("\nEnter 1 to go to the main menu and 0 to exit:");
scanf("%d",&main_exit);
system("cls");
if (main_exit==1)
menu();
else
close();
}
}
void erase(void)
{
FILE *old,*newrec;
int test=0;
old=fopen("record.dat","r");
newrec=fopen("new.dat","w");
printf("Enter the #account_no. you want to delete:");
scanf("%d",&rem.acc_no);
while (fscanf(old,"%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d",add.acc_no,add.name,add.dob.month,add.dob.day,add.dob.year,add.age,add.address,add.aadhar,add.phone,add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.deposit.year)!=EOF)
{
if(add.acc_no!=rem.acc_no)
fprintf(newrec,"%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d\n",add.acc_no,add.name,add.dob.month,add.dob.day,add.dob.year,add.age,add.address,add.aadhar,add.phone,add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.deposit.year);
else
{test++;
printf("\nKudos! Record deleted successfully!\n");
}
}
fclose(old);
fclose(newrec);
remove("record.dat");
rename("new.dat","record.dat");
if(test==0)
{
printf("\nSorry, Record not found!!\a\a\a");
erase_invalid:
printf("\nEnter 0 to try again,1 to return to main menu and 2 to exit:");
scanf("%d",&main_exit);
if (main_exit==1)
menu();
else if (main_exit==2)
close();
else if(main_exit==0)
erase();
else
{printf("\nInvalid!\a");
goto erase_invalid;}
}
else
{printf("\nEnter 1 to go to the main menu and 0 to exit:");
scanf("%d",&main_exit);
system("cls");
if (main_exit==1)
menu();
else
close();
}
}
void see(void)
{
FILE *ptr;
int test=0,rate;
int choice;
float time;
float intrst;
ptr=fopen("record.dat","r");
printf("Do you want to check with\n#1 Account no\n#2 Name\nEnter your choice:");
scanf("%d",&choice);
if (choice==1)
{ printf("Enter the #account_number:");
scanf("%d",&check.acc_no);
while (fscanf(ptr,"%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d",add.acc_no,add.name,add.dob.month,add.dob.day,add.dob.year,add.age,add.address,add.aadhar,add.phone,add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.deposit.year)!=EOF)
{
if(add.acc_no==check.acc_no)
{ system("cls");
test=1;
printf("\n#Account NO.:%d\n#Name:%s \n#DOB:%d/%d/%d \n#Age:%d \n#Address:%s \n#Aadhar No:%s \n#Phone number:%.0lf \n#Type Of Account:%s \n#Amount deposited:$ %.2f \n#Date Of Deposit:%d/%d/%d\n\n",add.acc_no,add.name,add.dob.month,add.dob.day,add.dob.year,add.age,add.address,add.aadhar,add.phone,
add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.deposit.year);
if(strcmpi(add.acc_type,"fixed1")==0)
{
time=1.0;
rate=9;
intrst=interest(time,add.amt,rate);
printf("\n\nYou will get $%.2f as interest on %d/%d/%d. Cheers!",intrst,add.deposit.month,add.deposit.day,add.deposit.year+1);
}
else if(strcmpi(add.acc_type,"fixed2")==0)
{
time=2.0;
rate=11;
intrst=interest(time,add.amt,rate);
printf("\n\nYou will get $.%.2f as interest on %d/%d/%d. Cheers!",intrst,add.deposit.month,add.deposit.day,add.deposit.year+2);
}
else if(strcmpi(add.acc_type,"fixed3")==0)
{
time=3.0;
rate=13;
intrst=interest(time,add.amt,rate);
printf("\n\nYou will get $.%.2f as interest on %d/%d/%d. Cheers!",intrst,add.deposit.month,add.deposit.day,add.deposit.year+3);
}
else if(strcmpi(add.acc_type,"saving")==0)
{
time=(1.0/12.0);
rate=8;
intrst=interest(time,add.amt,rate);
printf("\n\nYou will get $.%.2f as interest on %d of every month. Cheers!",intrst,add.deposit.day);
}
else if(strcmpi(add.acc_type,"current")==0)
{
printf("\n\nSorry, You will get no interest.\a\a");
}
}
}
}
else if (choice==2)
{ printf("Enter the #name:");
scanf("%s",&check.name);
while (fscanf(ptr,"%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d",add.acc_no,add.name,add.dob.month,add.dob.day,add.dob.year,add.age,add.address,add.aadhar,add.phone,add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.deposit.year)!=EOF)
{
if(strcmpi(add.name,check.name)==0)
{ system("cls");
test=1;
printf("\n#Account No.:%d\n#Name:%s \n#DOB:%d/%d/%d \n#Age:%d \n#Address:%s \n#Aadhar No:%s \n#Phone number:%.0lf \n#Type Of Account:%s \n#Amount deposited:$%.2f \n#Date Of Deposit:%d/%d/%d\n\n",add.acc_no,add.name,add.dob.month,add.dob.day,add.dob.year,add.age,add.address,add.aadhar,add.phone,
add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.deposit.year);
if(strcmpi(add.acc_type,"fixed1")==0)
{
time=1.0;
rate=9;
intrst=interest(time,add.amt,rate);
printf("\n\nYou will get $.%.2f as interest on %d/%d/%d. Cheers!",intrst,add.deposit.month,add.deposit.day,add.deposit.year+1);
}
else if(strcmpi(add.acc_type,"fixed2")==0)
{
time=2.0;
rate=11;
intrst=interest(time,add.amt,rate);
printf("\n\nYou will get $.%.2f as interest on %d/%d/%d. Cheers!",intrst,add.deposit.month,add.deposit.day,add.deposit.year+2);
}
else if(strcmpi(add.acc_type,"fixed3")==0)
{
time=3.0;
rate=13;
intrst=interest(time,add.amt,rate);
printf("\n\nYou will get $.%.2f as interest on %d/%d/%d. Cheers!",intrst,add.deposit.month,add.deposit.day,add.deposit.year+3);
}
else if(strcmpi(add.acc_type,"saving")==0)
{
time=(1.0/12.0);
rate=8;
intrst=interest(time,add.amt,rate);
printf("\n\n You will get $.%.2f as interest on %d of every month. Cheers!",intrst,add.deposit.day);
}
else if(strcmpi(add.acc_type,"current")==0)
{
printf("\n\nSorry, You will get no interest\a\a");
}
}
}
}
fclose(ptr);
if(test!=1)
{ system("cls");
printf("\nRecord not found!! Please Check again\a\a\a");
see_invalid:
printf("\nEnter 0 to try again,1 to return to main menu and 2 to exit:");
scanf("%d",&main_exit);
system("cls");
if (main_exit==1)
menu();
else if (main_exit==2)
close();
else if(main_exit==0)
see();
else
{
system("cls");
printf("\nInvalid!\a");
goto see_invalid;}
}
else
{printf("\nEnter 1 to go to the main menu and 0 to exit:");
scanf("%d",&main_exit);}
if (main_exit==1)
{
system("cls");
menu();
}
else
{
system("cls");
close();
}
}
void close(void)
{
printf("\n\n\n\nThis Program is developed by Group#5|C1");
}
void menu(void)
{ int choice;
system("cls");
system("color 2");
printf("\n\n\t\t\t\tVISHWAKARMA BANKING SERVICES");
printf("\n\n\n\t\t\t\xB2\xB2\xB2\xB2\xB2\xB2\xB2 >| WELCOME TO THE MAIN MENU |< \xB2\xB2\xB2\xB2\xB2\xB2\xB2");
printf("\n\n\t\t1.Create new account\n\t\t2.Update information of existing account\n\t\t3.For transactions\n\t\t4.Check the details of existing account\n\t\t5.Removing existing account\n\t\t6.View customer's list\n\t\t7.Exit\n\n\n\n\n\t\t Enter your choice:");
scanf("%d",&choice);
system("cls");
switch(choice)
{
case 1:new_acc();
break;
case 2:edit();
break;
case 3:transact();
break;
case 4:see();
break;
case 5:erase();
break;
case 6:view_list();
break;
case 7:close();
break;
}
}
int main()
{
char pass[10],password[10]="g5rox";
int i=0;
printf("\n\n\t\tEnter the #password to login:");
scanf("%s",pass);
if (strcmp(pass,password)==0)
{printf("\n\nPassword Match!\n\n\nLoading Program");
for(i=0;i<=6;i++)
{
fordelay(100000000);
printf(".");
}
system("cls");
menu();
}
else
{ printf("\n\nOops! Wrong password!!\a\a\a");
login_try:
printf("\nEnter 1 to try again and 0 to exit:");
scanf("%d",&main_exit);
if (main_exit==1)
{
system("cls");
main();
}
else if (main_exit==0)
{
system("cls");
close();}
else
{printf("\nInvalid!");
fordelay(1000000000);
system("cls");
goto login_try;}
}
return 0;
}
This program gives an compilation error in the midst when using any one of the services without providing any reason. I am unable to understand it either.
Compilation Error
A Detailed Soultion would be highly appreciated. Thanks!
You need to re-write this:
while(fscanf(ptr,"%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d\n",&add.acc_no,add.name,&add.dob.month,&add.dob.day,&add.dob.year,&add.age,add.address,add.citizenship,&add.phone,add.acc_type,&add.amt,&add.deposit.month,&add.deposit.day,&add.deposit.year)!=EOF)
{
//...
}
If fscanf() returns EOF that means the operation encountered an error, so your loop is terminated only when reading triggers an error.
Attempting to read "foobar" into an int variable is not an error, it's a matching failure.
-- added example ----
Eg... when the input buffer contains something other than a digit, this is an infinite loop
// assume input buffer contains "14/42\n"
unsigned sum = 0, i, j;
while (scanf("%u%u", &i, &j) != EOF) {
sum += i + j;
}
The first time through the loop, scanf() assigns 14 to i, meets the slash in input which triggers a matching failure and so returns with value 1. 1 is not EOF so the body of the loop executes (j is still unininitialized!!!) and the loop repeat with "/42" in the input buffer.
The 2nd time through the loop, the matching failure occurs with the very first character scanf() sees: the slash is not a valid character for "%u" so scanf return a value of 0. 0 is not EOF so the loop goes on forever.
Reading with fgets() consumes all of the input
char buf[100]; // large enough
unsigned sum = 0, i, j;
while (fgets(buf, sizeof buf, stdin)) {
// if (parse(buf, &i, &j) == 0) {
// sum += i + j;
// } else {
// printf(stderr, "error in input\n");
// }
}

Not able to know the reason of segmentation fault

I want make a tictactoe game program. It's unfinished yet but probably there are some problems that I can't figure out.
#include <stdio.h>
#include <string.h>
play(){
char input[3][3],player1[100],player2[100];
int i,j,k,times;
for (j=0;j<3;j++){
for (k=0;k<3;k++){
input[j][k]='_';
}
}
printf ("How many times do you want to play?\n");
scanf ("%d",&times);
printf ("Enter the name of first player : \n");
scanf ("%s",player1);
printf ("Enter the name of second player : \n");
scanf ("%s",player2);
printf ("Who will enter first letter?" "\n\n1. %s" "\n1. %s" "\n\nEnter 1 or 2 : \n",player1,player2);
scanf ("%d",&i);
for (j=0;j<times;j++){
for (k=0;k<9;k++){
if (i==1){
if (k==0 || k%2==0){
printf("This is %s's chance.",player1);
}
if (k==1 || k%2==1){
printf("This is %s's chance.",player2);
}
}
if (i==2){
if (k==0 || k%2==0){
printf("This is %s's chance.",player2);
}
if (k==1 || k%2==1){
printf("This is %s's chance.",player1);
}
}
printf ("%s %s %s\n\n%s %s %s\n\n%s %s %s\n\n",input[0][0],input[0][1],input[0][2],input[1][0],input[1][1],input[1][2],input[2][0],input[2][1],input[2][2]);
}
}
}
int main(){
int i;
printf("Welcome to TicTacToe made by Saurabh.\n\n1. Play\n2. Help\n\nEnter 1 or 2 : ");
scanf("%d",&i);
switch (i){
case 1:
play();
break;
case 2:
break;
default:
printf ("Invalid response from user.");
}
}
After running scanf("%d",&i) in the play function it says segmention fault but I can't figure out why that's happening. Thanks in advance.
With some prints I have seen there are some problems in this line:
printf ("%s %s %s\n\n%s %s %s\n\n%s %s %s\n\n",input[0][0],input[0][1],input[0][2],input[1][0],input[1][1],input[1][2],input[2][0],input[2][1],input[2][2]);
You defined char input[3][3] so input[0][0] is a single char (and the others with different indexes too) just like if I define char my_str[10];, my_str[0] is a single char.
I don't know if this is what you want but changing to:
printf ("%c %c %c\n\n%c %c %c\n\n%c %c %c\n\n",input[0][0],input[0][1],input[0][2],input[1][0],input[1][1],input[1][2],input[2][0],input[2][1],input[2][2]);
should not generate the error.

If(int IDnumvariable == structname[counter].IDnumber) Not working [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Im stuck on a situation with my book borrow function, The problem is when i have to compare user entered teacher id with an existing id in the teacherfile.
my id data types for both are integer so i used:
void tborrow() //2.1
{
int bksb=0;
int tbid2 =0;
struct books book[50];
struct teachers teach[50];
int x=0;
int c=0;
int i=0;
int tid=0;
int tid2=0;
int tbid=0;
FILE *teacherp;
FILE *bkbp;
teacherp= fopen("TeacherFile.txt", "r+");
if(teacherp!=NULL) //Checks if Teacher File was created successfully
{
printf("Teacher File Successfully Opened\n\n\n");
printf("Enter Teacher's ID# :");
scanf("%d",&tid);
while(1) // Loop till end of file
{
fflush(stdin);////flushes buffer
fscanf(teacherp,"%s %d %s %s %d ",teach[i].Teachname,&teach[i].IDnum,teach[i].contactnum,teach[i].Faculty,&teach[i].bksborrowed);
tid2= tid2 + teach[i].IDnum;
if (tid == tid2)
{
system("cls");
printf("Teacher ID Confirmed\n\n");
printf("\n\n----Teacher Information-----"); //check if correctly entered
printf("\nName: %s ", teach[i].Teachname);
printf("\nID #: %d " ,teach[i].IDnum);
printf("\nContact #: %s ", teach[i].contactnum);
printf("\nFaculty: %s " ,teach[i].Faculty);
printf("\nBooks Borrowed: %d " ,teach[i].bksborrowed);
printf("\n-----------------------------\n");
printf("\nIs your account? 1-Yes 0=No : ");
scanf("%d",&c);
fflush(stdin);//flushes buffer after scanf
if (c==1)//if yes find and borrow book
{
bksb = bksb+teach[i].bksborrowed;
if (bksb < 2)// if teacher has less than 2 books borrowed
{
printf("\nThis account currently has %d books borrowed",teach[i].bksborrowed);
bkbp = fopen("BookFile.txt","r+");
if(bkbp!=NULL) //Checks if Book File was created successfully if yes search for book and borrow
{
printf("Enter Book ISBN # :");
scanf("%d",&tbid);
while(1)
{
fscanf(bkbp,"%s %s %d %d %s %d %d-%d-%d %d-%d-%d ",book[x].Title, book[x].Author, &book[x].Accessionnum, &book[x].ISBN, book[x].Available, &book[x].bid, &book[x].bdate->m, &book[x].bdate->d, &book[x].bdate->y, &book[x].rdate->m, &book[x].rdate->d, &book[x].rdate->y);
tbid2 = tbid2 + book[x].ISBN;
if (tbid == tbid2)
{
printf("\n\n-------Book Information-------"); //check if correct book found
printf("\nTitle: %s", book[x].Title);
printf("\nAuthor: %s" ,book[x].Author);
printf("\nAccession#: %d" ,book[x].Accessionnum);
printf("\nISBN#: %d", book[x].ISBN);
printf("\nAvailability(Y-N): %s" ,book[x].Available);
printf("\nBorrowers ID#: %d ",book[x].bid);
printf("\nBorrow Date: %d-%d-%d ",book[x].bdate->m,book[x].bdate->d,book[x].bdate->y);
printf("\nReturn Date: %d-%d-%d ",book[x].rdate->m,book[x].rdate->d,book[x].rdate->y); //Prints user entry to screen for confirmation
printf("\n------------------------------\n");
printf("\nIs this the book you are looking for? 1-Yes 0=No : ");
scanf("%d",&c);
fflush(stdin);//flushes buffer after scanf
if (c==1)//if yes print into file
{
book[x].bid=tid2;
bksb++;
teach[i].bksborrowed=bksb;
printf("\n Book %s has been borrowed by %s %d",book[x].Title,teach[i].Teachname,teach[i].IDnum);
fclose(bkbp);
printf("\n\nReturning to previous account");
_getch();
break;
TeacherAcc();
}
/*else
{
fclose(bkbp);
system("cls");
printf("\nStarting over book borrowing!");
break;
tborrow();
}*/
}
else
//if we encountered the end of the file on the last attempt
//to read data then break out of the read loop
if( feof(bkbp) ) //If end of file is reached break out of loop
{
break;
}
++x;
}
}else // if book file failed to open
{
printf("Error!, Restarting Teacher Book Borrowing System. Press Enter to continue");
getchar();
tborrow();
}
}else if (teacher[i].bksborrowed == 2) // if teacher has already borrowed 2 books
{
printf("\nThis account already has %d books borrowed",teach[i].bksborrowed);
printf("\nGoing back to previous menu");
_getch();
system("cls");
TeacherAcc();
}
}
else if (c==0) //runs the Teacher borrow function if wrong account
{
system("cls");
printf("\nRe-Enter Teacher ID!");
tborrow();
}
}else // else if teacher id not found
{
printf("\nID %d not found, Please re-enter a valid ID \n Press enter to try again",tid);
_getch();
system("cls");
tborrow();
}
if( feof(teacherp) ) //If end of file is reached break out of loop
{
break;
}else
i++;
}//end of continuous loop
fclose(teacherp); //close the file when done
} //if file created successfully
else //Teacher file failed to load, restarts function to correctly open Teacher
{
printf("Error!, Restarting Teacher System. Press Enter to continue");
getchar();
system("cls");
}
printf("\n\nReturning to previous menu, Press Enter to continue \n");
fflush(stdin);//flushes buffer so getchar works properly
getchar();
system("cls");
TeacherAcc();
}//borrow function end
but it is not correctly comparing or storing the id i read from the file, and the file exists and the has the stored id for tests
attached is the block of code from my teacher borrow function
any help would be appreciated
i was thinking of making the id datatypes char and use strcmp(userentered,struct[count].idnum)
(form the comments)
Remove tid2= tid2 + teach[i].IDnum;.
Yes, you can use if (tid == teach[i].IDnum)
However, look at what your while(1) loop in tborrow is doing:
while(1)
read a teacher from the file
is the teacher the right one?
yes - do something
no - print an error and recursively call tborrow again.
Think about how you would do this if you were looking for a teacher by hand in a list on paper - would you look at the first teacher in the list, then give up and start again if it wasn't the right one?

Present error messages for invalid data entry

This is my first Project (kind of a text based game). How do I present error messages when text is entered in an area where numbers are prompted and vice versa. Or possibly the ability to reject improper input altogether.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char Name[20];
char q1;
int q2[2],q3[2];
float qT[3];
for(q1='n';q1!='y';)
{
printf("What is your name?\n");
gets(Name);
printf("You have entered: ");
puts(Name);
printf("Is this okay? [y/n]\n");
scanf("%s",&q1);
if(q1!='y'&&q1!='n')
printf("User error: '%c' not recognized.\nPlease enter 'y' to continue or 'n' to edit your name\n",&q1);
if(q1!='y'&&q1!='n')
scanf("%s",&q1);
}
printf("Okay, %s.",Name);
printf(" Out of the three choices which would you like to do most?\n1. Start a garden.\n2. Build a house.\n3. Travel to somewhere you've never been.\n");
scanf("%d",q2);
for (;q2[0]>3||q2[0]<1;)
{
printf("User error: '%c' not recognized.\nPlease enter one of the options given.",q2);
scanf("%d",q2);
}
if(q2[0]==1)
printf("What would you plant in your garden?\n1. Flowers\n2. Vegetables\n3. Fruit and Berries\n");
else
if(q2[0]==2)
printf("Where would you build your house?\n1. In the Mountains\n2. In the Desert\n3. By the Sea\n");
else
if(q2[0]==3)
printf("What would bring you to such a place?\n1. New faces and cultures\n2. Treasures and adventure\n3. Escape from the ordinary\n");
else
for(;q2[0]>3||q2[0]<1;)
{
printf("User error: '%c' not recognized.\nPlease enter one of the options given.",&q2);
scanf("%d",q3);
}
scanf("%d",q3);
qT[0]=(q2[0]*12)/q3[0];
printf("%f",qT[0]);
return 0;
}

C-Programming. Error in code that won't let me go to next function

The following code is a project I'm working on and after entering the details as in name and email it won't go to the next part of the code which is printing the price and then go to the next function. What did I do wrong??
Also, what can I do so that a customer can enter their details with spacing?
Thanks in advance.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int option,card_num,csc,phone_number;
char name,address,e_mail,registration;
void membership();
void payment();
int main()
{
membership();
return 0;
}
void membership()
{
printf("\tTHE CRUMP'S MEMBERSHIP");
printf("\n\n This membership ...");
printf("\n\n REGISTRATION [CONTRACTOR(A)/CORPORATION(B)]=");
scanf("%c",&registration);
switch (registration)
{
case 'A':
printf("\n\nEnter details without any spacing.");
printf("\nNAME:");
scanf("%s",&name);
printf("\nADDRESS:");
scanf("%s",&address);
printf("\nPHONE NUMBER:");
scanf("%d",&phone_number);
printf("\nE-MAIL:");
scanf("%s",&e_mail);
break;
case 'B':
printf("Enter details without any spacing.");
printf("\nNAME OF CORPORATION:");
scanf("%s",&name);
printf("\nADDRESS OF CORPORATION:");
scanf("%s",&address);
printf("\nPHONE NUMBER OF CORPORATION:");
scanf("%d",&phone_number);
printf("\nE-MAIL OF CORPORATION:");
scanf("%s",&e_mail);
break;
}
if (registration=='A')
printf("\n THE REGISTRATION FEE = |RM 50/MONTH |\t| RM 500/YEAR|");
else if (registration=='B')
printf("\n THE REGISTRATION FEE = |RM 200/MONTH |\t| RM 2200/YEAR|");
}
void payment()
{
printf("\n\nChoose method of payment: ");
printf("\n\t 1- Money Transfer \n\t 2-Debit Card\n");
scanf("%d",&option);
if (option==1)
{
printf("\nYou have chosen Money Transfer.");
printf("\nYou can transfer your money at our bank account --> 4365 4200 1471");
printf ("\n your membership will be confirmed when we have received the payment");
printf("\n************************************************************");
if (registration=='A')
{
printf("\nNAME:%s",name);
printf("\nADDRESS:%s",address);
printf("\nPHONE NUMBER:%d",phone_number);
printf("\nE-MAIL:%s",e_mail);
}
else if (registration=='B')
{
printf("\nNAME OF CORPORATION:%s",name);
printf("\nADDRESS OF CORPORATION:%s",address);
printf("\nPHONE NUMBER OF CORPORATION:%d",phone_number);
printf("\nE-MAIL OF CORPORATION:%s",e_mail);
}
printf("\n\n your transaction completed...\n\n Enjoy your membership discount.");
}
else if (option==2)
{
printf("\nYou have chosen Credit/Debit card.");
printf("\n Please enter your Credit/Debit card number:");
scanf("%d",&card_num);
printf("\n Please enter CSC code:");
scanf("%d",&csc);
printf("\nYour membership will be confirmed when we have received the payment");
printf("\n*********************************************************\n\n");
if (registration=='A')
{
printf("\nNAME:%s",name);
printf("\nADDRESS:%s",address);
printf("\nPHONE NUMBER:%d",phone_number);
printf("\nE-MAIL:%s",e_mail);
}
else if (registration=='B')
{
printf("\nNAME OF CORPORATION:%s",name);
printf("\nADDRESS OF CORPORATION:%s",address);
printf("\nPHONE NUMBER OF CORPORATION:%d",phone_number);
printf("\nE-MAIL OF CORPORATION:%s",e_mail);
}
printf("\n\n Your transaction is completed...\n\n Enjoy your membership discount.");
}
}
You are trying to read strings into char variables:
char name,address,e_mail,registration;
//...
scanf("%s",&name);
char only holds one character, not a string. If you want to read a string use an character array:
char name[100];
//...
and pass it to scanf like this:
scanf("%s",name);
because the array already decays to a pointer and taking the address is unnecessary.
Note that this requires you to set a limit for the name length. For example I choose 100-1 = 99 characters as limit. If the input is longer, undefined behaviour occurs, which is what you are experiencing right now.
Also note that you never call payment, so this will never be executed. If you want it to be executed after membership, then you need to call it:
int main()
{
membership();
payment();
return 0;
}
Your program has no call to payment() function thats why the program flow is not complete.

Resources