C issue: Program terminates itself - c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char choice;
struct {
char name[20];
int rn;
}read,write;
void wr(){
FILE *fp;
fp = fopen("record.txt","a+");
printf("Enter Your Name: ");
scanf("%s",write.name);
printf("Enter Your Roll Number: ");
scanf("%d",&write.rn);
fprintf(fp,"%s\t%d",write.name,write.rn);
fclose(fp);
menu();
}
void rd(){
FILE *fp;
fp = fopen("record.txt","r");
while(fscanf(fp,"%s %d",read.name,&read.rn)!= EOF){
printf("%s\t%d\n",read.name,read.rn);
}
fclose(fp);
getche();
menu();
}
void menu(){
system("cls");
printf("Do you want to read/write/exit the data R/W/E: ");
scanf("%c",&choice);
tolower(choice);
if(choice == 'w'){
wr();
}
else if(choice == 'r'){
rd();
}
else if(choice == 'e'){
exit(1);
}
}
int main() {
menu();
getche();
system("cls");
return 0;
}
I want to terminate it when user enters 'e' but it terminates after every information entry as well as I read data.
Means after every time read or write function works and the program should ask again about the choice it terminates.

You need to use a for or a while loop like so:
int main()
{
while(1) // while true
{
menu();
getche();
system("cls");
}
return 0;
}
You are already calling exit(1) in your else if of menu(), so add the while(true) and it will work as you want it to.

Related

Bugs in C Switch Menu using a Char as Choice, Won't Read in fgets name

Im basically Writing a program that creates, reads, updates and
deletes records in a binary file.
Everything compiles correctly, no syntax errors, but I do have some
bugs.
KNOWN BUGS
1.) Imputing any strings does not work, using fgets
2.) Ctrl-D Does Work but outputs a 'default' error before it exits.
3.) Update does not work (Not my main issue at the moment as the others are more important for now.)
4?) I'm not sure if the menu is working how it's supposed to work. I
think the do while is correct, since in the menu if I select and hit
CTRL-D it does exit the program. Just wanna be sure.
Right now I just want to know why, It is skipping the courseName in
the inputs function.
Here is my code thus far
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <errno.h>
#include <string.h>
typedef struct{
char courseName [64];
char courseSched [4];
unsigned int courseHours;
unsigned int courseSize;} COURSE;
FILE *pfileCourse;
int courseNumber = 0;
//Prototypes
void inputDetails(COURSE *c);
void readCourseRecord();
void createCourseRecord();
void print_menu();
void modifyCourseInfo();
void deleteCourse();
void display(COURSE c);
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
char choice; // this is the choice
printf("Enter one of the following actions or press CTRL-D to exit\n");
printf("C - Create a new course record\n");
printf("R - Read an existing course record\n");
printf("U - Update an existing course record\n");
printf("D - Delete an existing course record\n");
do{
choice = getchar();
switch(choice) {
case 'c':
case 'C':
printf("YOU PICKED C for Create\n");
createCourseRecord();
break;
case 'r':
case 'R':
printf("This is Choice R\n");
readCourseRecord();
break;
case 'u':
case 'U':
printf("Here is where you update an existing course\n");
modifyCourseInfo();
break;
case 'd':
case 'D':
printf("here is where you Delete an existing course record\n");
deleteCourse();
break;
default:
printf("Wrong Choice!\n");
}
}while(choice != EOF);
return 0;
}
void createCourseRecord() {
COURSE data;
pfileCourse = fopen("courses.dat", "ab");
printf("Please Enter The Details of The Course\n");
inputDetails(&data);
fwrite(&data, sizeof(data), 1, pfileCourse);
fclose(pfileCourse);
printf("Course Has Been Created!\n");
}
void inputDetails(COURSE *c) {
printf("Enter a course number: \n");
scanf("%d", &courseNumber);
printf("Enter a Course Name: \n");
fgets(c->courseName, sizeof(courseName), stdin);
printf("Enter the course schedule (MWF or TR): \n");
fgets(c->courseSched, 4, stdin);
fflush(stdin);
printf("Enter the course credit hours: \n");
scanf("%d",&c->courseHours);
fflush(stdin);
printf("Enter Number of Students Enrolled: \n");
scanf("%d",&c->courseSize);
return;
}
void readCourseRecord(){
COURSE data;
int flag = 0;
int readCourseNumber = 0;
printf("Please Enter a Course Number to Display\n");
scanf("%d", &readCourseNumber);
fflush(stdin);
pfileCourse = fopen("courses.dat", "rb");
while((fread(&data, sizeof(data), 1, pfileCourse)) > 0) {
if(readCourseNumber == courseNumber)
{
display(data);
flag = 1;
}
}
fclose(pfileCourse);
if(flag == 0)
printf("Course not Found!\n");
}
void deleteCourse(){
int newCourseNum;
COURSE data;
FILE *file2;
printf("Please Enter The Course You Wish You Delete\n");
scanf("%d", &newCourseNum);
pfileCourse = fopen("courses.dat", "rb");
file2 = fopen("temp.dat", "wb");
rewind(pfileCourse);
while((fread(&data, sizeof(data), 1, pfileCourse)) > 0)
{
if(courseNumber != newCourseNum)
{
fwrite(&data, sizeof(data), 1, file2);
}
}
fclose(file2);
fclose(pfileCourse);
remove("courses.dat");
rename("temp.dat", "courses.dat");
printf("%d was Successfully deleted\n", newCourseNum);
}
void modifyCourseInfo()
{
COURSE data;
int newCourseNum, found = 0;
printf("Modify\n");
printf("Please Enter The Course You Wish You Modify\n");
scanf("%d", &newCourseNum);
pfileCourse = fopen("courses.dat", "rb+");
while ((fread(&data, sizeof(data), 1, pfileCourse)) > 0 && found == 0)
{
if (courseNumber == newCourseNum)
{
display(data);
printf("Please Enter New Details\n");
inputDetails(&data);
fseek(pfileCourse, - (long)sizeof(data), 1);
fwrite(&data, sizeof(data), 1, pfileCourse);
printf("Course Updated\n");
found == 1;
}
}
fclose(pfileCourse);
if(found == 0)
printf("ERROR: course not found\n");
}
void display(COURSE c){
printf("courseNumber:\t %d\n", courseNumber);
printf("courseName:\t %s\n",c.courseName);
printf("courseSched:\t %s\n",c.courseSched);
printf("courseName:\t %d\n",c.courseHours);
printf("courseSize:\t %d\n",c.courseSize);
}
It doesn't skip courseName, courseName just gets value '\n' because scanf function stops reading your input BEFORE white space. Scanf ignores any whitespace characters encountered before the next non-whitespace character. So you can just add
scanf("%d[^\n]", &courseNumber);
getchar();
after every scanf you have but I'd recommend you to use fgets function for every interactive input.

making a program to add a list of names in 2d array actually I just made a part of it and I have a lot of errors

my code is:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char names[10][31];
int u=0;
char new[31];
int ctr=1;
int notInList=0;
int y=0;
int i=0;
char *p;
strcpy(names[0],"mahmoud");
while(1)
{
printf("\t\t§§§Menu items§§§\n");
printf("1==>enter a new name\n");
printf("2==>search for a name\n");
printf("3==>delete a name from the list\n");
printf("Note !!.. ((if you want to exit the program press(1)and then type ((exit))\n");
fflush(stdin);
scanf("%i",&u);
notInList=1;
if(u==1)
{
printf("please enter a name : ");
fflush(stdin);
gets(new);
_strlwr(new);
if(strcmp(new,"exit")==0)
{
printf("bye bye\n");
break;
}
else
{
notInList=1;
for(int i=0;i<=ctr;i++)
{
p=strstr(new,names[i]);
if(strcmp(new,names[i])==0)
{
printf("the name is already exist\n");
break;
}
else if (p)
{
printf("did you mean (( %s ))\n",names[i]);
printf("1==>yes\n");
printf("2==>no\n");
fflush(stdin);
scanf("%d",&y);
if(y==1)
{
printf("the name is already exist\n");
break;
}
else if(y==2)
{
notInList=0;
strcpy(new,names[ctr]);
ctr++;
break;
}
else printf("plz enter a number from the list");
}
else
{
notInList=0;
}
}
if(notInList==0)
{
strcpy(new,names[ctr]);
ctr++;
for(int i=0;i<ctr;i++);
{
printf("%d==>%s\n",i+1,names[i]);
}
}
// break;
}
}
return 0;
}
the first problem is: when I enter ( 1) and then add a name is similar to the first name it printf to me did you mean ( )//// without a name
the second is when I want to add a new name it doesn't please help me
notice that he program is not finished only the first choise

Correction request for C Program

// I'm having issues compiling my program. Honestly, i'm a new programmer and i'm not really sure how to use certain things within my program. Can someone check my program and give me the corrections please or better thoroghly explain it ti me? It's neede for monday..//
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#include <time.h>
int main()
{
//File declarations//
FILE*Log;
FILE*Inventory;
FILE*Username;
char fpass_word[10]="invent";
char fusername[10]="";
//Declarations for variables//
int main;
int sub_main;
int s=0;
int s_goods;
int p_goods;
int in_goods;
int c_goods;
double Unit_price;
int item_quantity;
int invoice_num;
char pass_word1[10]=" ";
char pass_word[10]="invent";
char username[10]="inventor";
char username1[10]=" ";
char Supplier[12]=" ";
char Items_name[12]=" ";
char Invoice_date[10]=" ";
//Declarations for variables//
int u=0;
int count=0;
int option;
int choice;
int choice1;
int m=0;
int Save;
int New_inventory;
int Update_inventory;
int Print;
int Close_Program;
int t_sales;
int t_purchases;
double m_sales[4]={30000.00,50000.00,100000.00,120000.00};
}
Log=fopen("Invent.txt","w")
if(Log==NULL)
printf("File does not exist");
}
else
{
fprintf(Log,"%s",pass_word);
fclose(Log);
}
user=fopen("Username.txt","w")
if(user==NULL)
{
printf("File does not exist");
}
else
{
fprintf(user,"%s",username);
fclose(user);
}
printf("__________________________________________________________\n\n");
printf("************Please login to your account!************\n\n");
printf("__________________________________________________________\n\n");
printf("Please enter your username: \n");
scanf("%s",username);
user=fopen("Username.txt","r")
{
if(user==NULL)
{
printf("File does not exist");
}
else
{
fprintf(user,"%s",fusername);
fclose(user);
}
choice1=strncmp(username,fusername,10);
printf("Please enter password: \n");
scanf("%s",pass_word1);
Log=fopen("Invent.txt","r")
if(Log==NULL)
{
printf("File does not exist");
}
else
{
fscanf(Log,"%s",fpass_word);
fclose(Log);
}
choice=strncmp(pass_word1,fpass_word,10);
while (choice!=0 && count<3)
{
printf("*************************************************************************************\n\n");
printf("!!!!!!!!!!!!!!!!!!!!!!!!Please re-enter your login info!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
printf("*************************************************************************************\n\n");
printf(" Please enter username: \n");
scanf("%s",&username);
choice=strncmp(username,username1,10);
printf("Please enter password!\npassword:");
scanf("%s",pass_word);
choice=strncmp(pass_word,pass_word1,10);
count=count++;
//menu function!!!
getch();
system("cls");
}//login page
printf("\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
printf("\n******************** Welcome to the INVENT BIZ main page!********************\n\n");
printf("\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n");
printf (">>>>>>>>>>>>>>> Please select an option you desire:<<<<<<<<<<<<<<<\n\n");
printf("1: New inventory\n");
printf("2: Update inventory\n");
printf("3: Print\n");
printf("4: Save \n");
printf("5: Close Program\n");
printf("Please select an option: \n");
scanf("%d",&option);
//menu screen
while(option!=6)
{
switch(main)
{
case 1:
printf("New inventory");
Inventory=fopen("New Inventory.txt","w")
if (Inventory==NULL)
printf("This File is empty!");
}
else
{
fprintf("Please enter invoice date:\t\n");
fprintf("Please enter Supplier:\t\n");
fprintf("Please enter Item name:\t\n");
fprintf("Please enter quantity of items:\t\n");
fprintf(" Please enter invoice number:\t\n");
fprintf("Please enter Unit Price:\t\n");
}
fclose(Inventory);
// Data entered for inventory//
switch(sub-main)
{
case 10:
printf("Please enter sales for each month:%d",t_sales);
printf(" Total Sales\n");
scanf("%d",&t_sales);
break;
case 3:
printf("Print");
Inventory=fopen("New Inventory.txt","r")
fscanf(Inventory,"%d",Invoice_date);
fscanf(Inventory,"%s",Supplier);
fscanf(Inventory,"%s",Items_name);
fscanf(Inventory,"%d",&item_quantity);
fscanf(Inventory,"%d",&invoice_num);
fscanf(Inventory,"%d",&Unit_price);
fclose(Inventory);
break;
case 4:
printf("Save");
Inventory=fopen("Inventory1.txt","w");
if(Inventory==NULL)
{
printf("This file empty!!!");
}
else
{
printf("File saved");
}
fclose(Inventory);
case 5:
printf("Close Program");
exit(main);
break;
} // end switch
system("cls");
printf (">>>>>>>>>>>>>>> Please select an option you desire!!!<<<<<<<<<<<<<<<\n\n");
printf("1: New inventory\n");
printf("2: Update inventory\n");
printf("3: Print\n");
printf("4: Save \n");
printf("Please select an option: \n");
scanf("%d",&option);
}
}
system("cls");
getch();
return ();
}
You should really be more specific and not just throw down an entire program and say you want to someone to clean it up for you.
Thank being said I noticed right away you had a few improperly placed curly braces. Your very first if statement is missing an opening brace and further down you have an unnecessary opening brace after user=fopen("Username.txt", "r")
Beyond that indentation is completely off throughout and your switch statements make it really hard to follow what it is you're trying to accomplish with them.
My advice is to read through the compiler errors and locate each issue one by one, and if you're having a problem you can't solve then be specific and post the errors you're getting with your program.

C - Function not executing?

The 1. and 3. menu items are working, but if I choose the 2. menu item it's not listing my data. Why is that?
(It has to be compiled and run in linux command line [NO IDE!])
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <time.h>
struct log{
int id;
char name[20];
char location[20];
int quantity;
char quantity_type[10];
time_t added;
};
char fname[] = "data2.dat";
void add();
void listAll();
int nextId();
int main(){
int ch;
while(1){
system("clear");
printf("///Log stuff!///\n\n");
printf("1. Add\n");
printf("2. List all\n");
printf("0. Exit\n");
printf("\n///////////////////////////////\n\n");
printf("Choose a number from the menu: ");
scanf("%d", &ch);
switch(ch){
case 1: add();
break;
case 2: listAll();
break;
case 0: exit(0);
break;
}
}
return 0;
}
void add(){
FILE *f;
struct log log;
f = fopen(fname, "ab");
if(f == NULL){perror("Can't open!\n");}
log.id = nextId();
printf("\nName: ");
scanf("%s", log.name);
printf("\nLocation: ");
scanf("%s", log.location);
printf("\nQuantity: ");
scanf("%d", &log.quantity);
printf("\nQuantity type: ");
scanf("%s", log.quantity_type);
log.added = time(NULL);
fwrite(&log,sizeof(log),1,f);
fclose(f);
}
void listAll(){
FILE *f;
struct log log;
f = fopen(fname,"rb");
if(f == NULL){perror("Can't open!\n");exit(1);}
printf("\n///////////////////////////////\n\n");
printf("\tList of all data\n\n");
printf("///////////////////////////////\n\n");
while(fread(&log,sizeof(log),1,f) == 1){
printf("%d\t",log.id);
printf("%s\t",log.name);
printf("%s\t",log.location);
printf("%d\t",log.quantity);
printf("%s\t",log.quantity_type);
printf("%s",ctime(&log.added));
}
printf("\n///////////////////////////////\n\n");
fclose(f);
}
int nextId(){
FILE *f;
struct log log;
int id = 1;
f = fopen(fname, "rb");
if(f == NULL){perror("Can't open!\n");}
while(!feof(f)){
fread(&log, sizeof(log), 1, f);
if(log.id >= id){id = log.id + 1;}
}
fclose(f);
return id;
}
Is there a more elegant way to do this task?
This menu display/input choice/switch section of the code has a logic error
the screen is being cleared before the user has a chance to look at any displayed data.
Proper placement of calls to system(clear) and getchar() will fix the problem
a function should only have 1 normal exit. Any other exit points should be only for error conditions
You might try the following:
system(clear);
int done = 0;
while( !done )
{
printf("///Log stuff!///\n\n");
printf("1. Add\n");
printf("2. List all\n");
printf("3. Exit\n");
printf("\n///////////////////////////////\n\n");
printf("Choose a number from the menu: ");
if( 1 != scanf("%d", &ch) )
{ // then scanf failed
perror( "scanf for menu choice failed" );
exit( EXIT_FAILURE );
}
// implied else, scanf successful
// eliminate menu from screen
system(clear);
switch(ch)
{
case 1:
add();
break;
case 2:
listAll();
printf( "\npress any key to continue\n" );
getchar();
break;
case 3:
done=1;
break;
default:
printf("\nyou entered an invalid menu selection, try again\n");
break;
} // end switch
} // end while

Calling the function directly works but calling from another function fails

When I use the display_menu function to call read_txt_file() it doesn't work. I am unable to get the file contents to the stdout but when I use the read_txt_file() directly, it works. I can see the contents of the file in stdout. What is the problem with the display_menu?
#include <stdio.h>
typedef struct filename
{
int age;
char name[100];
}name_t;
name_t * fname=NULL;
void quit()
{
printf("\nPress enter to exit");
fflush(stdin);
getchar();
}
enter(char prompt[])
{
puts(prompt);
fflush(stdin);
getchar();
}
void read_txt_file()
{
char ch;
fname=(name_t *)malloc(sizeof(name_t));
FILE *fptr=NULL;
atexit(quit);
printf("Please enter the file name to read : ");
fflush(stdin);
scanf("%s",fname->name);
fptr=fopen(fname->name,"r");
if(fptr == NULL)
{
perror("Could not open the file ");
return;
}
printf("+++++++++++++++++++++++++++++++++++++++++++++++++");
printf("Contents of the file %s are : ",fname->name);
**while(ch != EOF)
{
ch=fgetc(fptr);
printf("%c",ch);
}**
enter("press enter");
fclose(fptr);
}
display_menu()
{
int choice;
while(1)
{
system("cls");
printf("\t\t1.read and display from a file\n \
\b2.quit\n");
scanf("%d",&choice);
switch(choice)
{
case 1 :
read_txt_file();
break;
case 2 :
exit(0);
default :
printf("please enter proper choice(1-3)\n Enter to continue");
fflush(stdin);
getchar();
}
}
}
int main()
{
/*
read_txt_file();
*/
**display_menu();**
return 0;
}
After the scanf("%d",&choice); call, the input will still have a '\n' (the one of the return you pressed to enter the choice). So the file name will be empty. You can add a getchar() after reading the choice (to remove the '\n').

Resources