Edit my struct in C with pointer - c

I want to create an edit function that receives as a parameter by reference the vector of songs. (using pointers)
The user must choose the song number and re-enter the data of that position of the vector.
I created the struct, I am already receiving the values and I am playing. But I do not know how to edit. Anyone to help me start this part?
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <locale.h>
#include <string.h>
struct registry_of_music {
char name[50];
char artist[60];
char url[80];
};
struct registry_of_music music[9];
int main() {
int i;
printf("\nRegistry of Music\n\n\n");
for(i = 0; i <= 3;i++ ){
printf("Name of Music: ");
fflush(stdin);
fgets(music[i].name, 50, stdin);
printf("Name of Artist: ");
fflush(stdin);
fgets(music[i].artist, 60, stdin);
printf("URL of Internet: ");
fflush(stdin);
fgets(music[i].url, 80, stdin);
}
int op;
do
{
printf("1 - Play\n");
printf("2 - Edit\n");
printf("3 - Exit\n");
printf("Please enter a value:");
scanf("%d", &op);
switch(op) {
case 1: play();
break;
case 2: edit();
break;
case 3: printf("Bye\n");
break;
default: printf("Try Again\n");
}
} while (op!=3);
getch();
return(0);
}
void play(){
int i;
for(i = 0; i <= 3;i++ ){
printf("Name ...........: %s", music[i].name);
printf("Artist .....: %s", music[i].artist);
printf("URL .....: %s", music[i].url);
}
}
void edit(){}

The «fill instance of structure» action is absolutely identical if performing on uninitialized structure or initialized. Even if an instance is not initialized, it has some rubbish values in its fields.
On the other hand there is no way to specify default value which will be shown in fgets's prompt and will be available for keyboard edit, unless you're using much more complicated (and NOT included in ISO C standard) tools.

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.

.exe has stopped working (Cprogramming)

I am running this program and keep getting an error after I input my name
"program1.exe has stopped working"
have no idea why any help?
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
void create();
//void edit();
//void delete();
int main()
{
char choice;
printf("\n\t\t **********************\n\n");
printf("\n\t\t Train Booking Application\n");
printf("\n\t\t **********************\n\n");
printf("Select 1 to create a booking,\tSelect 2 to Edit booking,\tSelect 3 to Delete a booking\n");
scanf("%d",&choice);
if (choice == 1){
create();
}
return 0;
}
void create(){
char Fname,Sname;
printf("Please enter your First name:\n");
scanf ("%s",Fname);
printf("Please enter your Second name:\n");
}
char is used to read one character. Use string instead.
%d is used for reading integers but you defined . Either use
int choice;
or use
scanf("%s", &choice);
try to use a switch for your selection too
switch(choice){
case 1:
create();
break;
case default:
//default statement(s)
}
Please pay attention to the compiler warnings. It will discover problems for you. Suggestion for improvements in the program comments:
#include <stdio.h>
#include <stdlib.h>
//#include <iostream> // C++ include, not needed!
void create();
int main()
{
int choice; // changed to int to match scanf("%d", char is to small to hold an `int`
printf("\n\t\t **********************\n\n");
printf("\n\t\t Train Booking Application\n");
printf("\n\t\t **********************\n\n");
printf("Select 1 to create a booking,\tSelect 2 to Edit booking,\tSelect 3 to Delete a booking\n");
scanf("%d", &choice);
switch (choice){ // switch is a better choice than nested ifs
case 1:
create();
break;
default:
printf("not implemented yet...\n");
break;
}
return 0;
}
void create(){
char Fname[256],Sname[256]; // changed to arrays to match scanf ("%s"
// char Fname, Sname with %s would destroy memory
printf("Please enter your First name:\n");
scanf ("%s",Fname);
printf("Please enter your Second name:\n");
scanf ("%s",Sname);
}
As char just store one character and your name is longer than that, try using char Fname[], for storing your entire name.

Error: c:87:(.text+0x247): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `course_insert'

I'm brand new to C and I'm trying to figure out what in the world is causing this. Another similar question said that I had to download another library but that hasn't fixed the issue. So, hopefully someone can spot my problem.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum Subject {SER=0, EGR=1, CSE=2, EEE=3} subject;
struct Course {
enum Subject subject;
int number;
char teacher[1024];
int hours;
} *course;
//place to store course information
struct Course* CourseCollection = NULL;
//number of courses in the collection. also the index of the next empty element.
int courseCount = 0;
void branching(char option);
void course_insert(struct Course course);
int main() {
char input_buffer;
printf("Welcome to ASU Class Schedule\n");
//menu and input loop
do {
printf("\nMenu Options\n");
printf("------------------------------------------------------\n");
printf("a: Add a class\n");
printf("d: Drop a class\n");
printf("s: Show your classes\n");
printf("q: Quit\n");
printf("\nTotal Credits: %d\n\n", courseCount);
printf("Please enter a choice ---> ");
scanf(" %c", &input_buffer);
branching(input_buffer);
} while (input_buffer != 'q');
return 0;
}
//takes a character representing an inputs menu choice and calls the appropriate
//function to fulfill that choice. display an error message if the character is
//not recognized.
void branching(char option) {
int prefix, courseNum, credits;
char instructor;
struct Course course1;
switch(option) {
case 'a' :
printf("Adding a class");
printf("\nWhat is the subject (SER=0, EGR=1, CSE=2, EEE=3)? ");
scanf(" %d", &prefix);
course1.subject = prefix;
printf("\nWhat is the course number (e.g. 334)? ");
scanf(" %d", &courseNum);
course1.number = courseNum;
printf("\nHow many credits is the class? ");
scanf(" %d", &credits);
course1.hours = credits;
printf("\nWhat is the name of the teacher? ");
scanf(" %s", &instructor);
strlcpy(course1.teacher, instructor, 1024);
printf(" %s %d", course1.subject, course1.number);
courseCount++;
course_insert(course1);
break;
case 'd' :
// TODO
break;
case 's' :
// TODO
break;
case 'q' :
printf("Goodbye ");
break;
default :
printf("Error: Invalid Input. Please Try Again. ");
break;
}
void course_insert(struct Course course) {
CourseCollection = malloc(sizeof(course)*courseCount);
}
}
The problem is a syntactical bug; the function definition for course_insert() is inside the curly braces of the function definition of branching(). You need to fix the curly braces:
void branching (char option)
{
// Code for function
}
void course_insert(struct Course course)
{
CourseCollection = malloc(sizeof(course)*courseCount);
}

why my program stops working when type enter?

My main goal for this code is to capture the users input and do whatever he wants to do with the choices I have presented, but I'm stuck: when I compile, I can only type the word and the program stops working.
i have no idea where I'm making a mistake.
The is my code:
#include <stdio.h>
#include <string.h>
#define MAX_STRING_LENGTH 100
void grab_user_input(void);
void load_menu(void);
void Count_the_letters(void);
int main(void)
{
grab_user_input();
return 0;
}
void grab_user_input(void)
{
char word;
{
printf("Please enter a single word (25 characters or less): \n");
scanf("%s", &word);
printf("Thanks! The word you entered is: %s\n", word);
}
void load_menu(void)
{
int choice;
do
{
int choice;
printf("\n(:===Menu====:)\n");
printf("1. Count_the_letters\n");
printf("2. Count_the_vowels\n");
printf("3. Reverse_the_word\n");
printf("4. Check_if_palindrome\n");
printf("5. Enter_a_new_word\n");
printf("6. Exit\n");
scanf("%d", &choice);
switch (choice)
{
case 1: Count_the_letters();
break;
}
} while (choice != 3);
}
void Count_the_letters(void)
{
char S[MAX_STRING_LENGTH];
int count;
count = 0;
do {
printf("string:\t");
scanf("%s",S);
if (strcmp(S,"exit") != 0)
++count;
} while (strcmp(S,"exit") != 0);
printf("word count:\t%d\n", count);
}
return 0;
}
scanf("%s", &word);
needs an array of characters to read the data. &word only has space for one character.
You are running into undefined behavior.
Use
char word[26];
scanf("%25s", &word);
The reason is that you are passing the address to the char variable you declared and scanf() is trying to write two bytes where it only fits one.
char word
this declares a char variable, it can hold a single byte
scanf("%s", &word);
whill require at least one byte for an empty string the '\0'.
But also, you declared a lot of functions inside void grab_user_input(void), that is not valid standard c, it might work with some compiler, but it's not standard.

2 Dimensional Array address Book having issues with fgets

This is my assignment:
Create a program that allows a user to enter up to 10 addresses of friends. Use a two dimensional array to store the address of friends’. After each address is entered, the user should have the option to enter another address or print out a report that shows each addresses entered thus far.
I get most of it but I am having my main issue with fgets. I keep getting this error:
warning: passing arg 1 of `fgets' makes pointer from integer without a cast
The code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main ()
{
char name[20]= {0};
char address[40]= {100};
int choice;
int i;
printf("Welcome to the Address Book!\n\n");
for (i=0;i<10;i++) //start of the array loop. should give an exit after each entry
{
printf("Would you like to (1)Enter an address, or (2)Print the address book?\n");
scanf("%i",&choice);
switch (choice)
{
case 1:
{
printf("Please enter a name...\n");
fgets(name[i],20,stdin);
printf("You entered %s .", name);
printf("Please enter an address...\n");
fgets(address[i],40,stdin);
printf("You enteres %s .", address);
}
break;
case 2:
for (i = 0; i<10; i ++)
{
printf("%s\n", name[i]);
printf("%s\n", address[i]);
}
break;
}
}
return (0);
}
Find the corrected code in below
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main ()
{
char name[10][20]; //Fix3
char address[10][40];//Fix4
int choice;
int i, j;
printf("Welcome to the Address Book!\n\n");
for (i=0;i<10;i++) //start of the array loop. should give an exit after each entry
{
printf("Would you like to (1)Enter an address, or (2)Print the address book?\n");
scanf("%i",&choice);
switch (choice)
{
case 1:
{
printf("Please enter a name...\n");
getchar(); //Fix1
fgets(name[i],20,stdin);
printf("You entered %s .", name);
printf("Please enter an address...\n");
//getchar();//Fix2
fgets(address[i],40,stdin);
printf("You enteres %s .", address);
}
break;
case 2:
{
for (j = 0; j<i; j ++)
{
printf("%s\n", name[j]);
printf("%s\n", address[j]);
}
}
break;
}
}
return (0);
}
The corrections are:
2D array is used to get the name and address
getchar() is called to consume '\n' before using fgets();

Resources