After running the next code, in the function get_data(), everything runs normally until I get to the end of the For, when program should call the function continue_function() but in somehow, ignores it, and the program just ends.
Am I calling it in a wrong way?
I'm just start learning programming in C and this is one of the last exam's exercises.
#include <stdio.h>
#define MAX 100
#define YES 1
#define NO 0
struct record
{
char fname[15+1];
char lname[20+1];
char phone[9+1];
long income;
int month;
int day;
int year;
};
struct record list[MAX];
int last_entry = 0;
void get_data(void);
void display_report(void);
int continue_function(void);
void clear_kb(void);
main()
{
int cont = YES;
int ch;
while(cont == YES)
{
printf("\n");
printf("\n MENU");
printf("\n =========\n");
printf("\n1. Enter Names");
printf("\n2. Print Report");
printf("\n3. Quit");
printf("\n\nEnter Selection ==> ");
scanf("%d", &ch);
clear_kb();
system("cls");
switch(ch)
{
case 1: get_data();
break;
case 2: display_report();
break;
case 3: printf("\n\nThank You for using this Program!");
cont = NO;
break;
default: printf("\n\nInvalid Choice, Please Select 1 to 3!");
break;
}
}
}
void get_data(void)
{
int cont;
int ctr;
for(cont = YES; last_entry < MAX && cont == YES; last_entry++)
{
printf("\n\nEnter information for Person %d.", last_entry+1);
printf("\n\nEnter first name: ");
gets(list[last_entry].fname);
printf("Enter last name: ");
gets(list[last_entry].lname);
printf("Enter phone in 123-4567 format: ");
gets(list[last_entry].phone);
printf("Enter Yearly Income: ");
scanf("%ld", &list[last_entry].income);
printf("Enter Birthday: ");
do
{
printf("\n\tMonth (0 - 12): ");
scanf("%d", &list[last_entry].month);
}
while (list[last_entry].month < 0 || list[last_entry].month > 12);
do
{
printf("\tDay (0 - 31): ");
scanf("%d", &list[last_entry].day);
}
while (list[last_entry].day < 0 || list[last_entry].day > 31);
do
{
printf("\tYear (1800 - 2025): ");
scanf("%d", list[last_entry].year);
}
while (list[last_entry].year < 1800 || list[last_entry].year > 2025);
cont = continue_function();
}
if(last_entry == MAX)
{
printf("\n\nMaximum Number of Names has been entered!\n");
}
}
void display_report(void)
{
long month_total = 0, grand_total = 0;
int x, y;
fprintf(stdout, "\n\n");
fprintf(stdout, "\n REPORT");
fprintf(stdout, "\n ========");
for(x = 0; x <= 12; x++)
{
month_total = 0;
for(y = 0; y < last_entry; y++)
{
if(list[y].month == x)
{
fprintf(stdout, "\n\t%s %s %s %ld", list[y].fname, list[y].lname, list[y].phone, list[y].income);
month_total += list[y].income;
}
}
fprintf(stdout, "\nTotal for month %d is %ld:", x, month_total);
grand_total += month_total;
}
fprintf(stdout, "\n\nReport Totals:");
fprintf(stdout, "\nTotal Income is %ld", grand_total);
fprintf(stdout, "\nAverage Income is %ld", grand_total/last_entry);
fprintf(stdout, "\n\n* * * End of Report * * *");
}
int continue_function(void)
{
char ch;
printf("\n\nDo you wish to continue? (Y)es/(N)o: ");
getc(ch);
while(ch != 'n' && ch != 'N' && ch != 'y' && ch != 'Y')
{
printf("\n%c is invalid!", ch);
printf("\n\nPlease enter \'N\' to Quit or \'Y\' to Continue: ");
getc(ch);
}
clear_kb();
if(ch == 'n' || ch == 'N')
{
system("cls");
return(NO);
}
else
{
system("cls");
return(YES);
}
}
void clear_kb(void)
{
char junk[80];
gets(junk);
}
You're not using your get functions properly:
https://www.tutorialspoint.com/c_standard_library/c_function_getc.htm
int getc(FILE *); for instance requires a FILE* as argument and returns the character, but you are passing the character as argument, it should look like ch = getc(stdin);.
On another note, notice that when you use scanf you pass &c? This is because for a value to be modified, you need to pass the address where it's stored (&) and not the value itself. So even if getc took a char, it would have to be getc(&ch).
You should follow a quick tutorial on pointers and types, if you come from a higher level language or if you're new that could be a good idea.
Related
Why am I getting this error? I'm fairly new to C just wondering what could have happened. Getting this error mainly main.c:14:10: error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘attribute’ before ‘=’ token. Tried fixing the error to no avail. When I remove the '-1' after int code, it compiles but not what I want it to compile. Thanks again.
#include<stdio.h>
#include<stdlib.h>
struct event {
int code = -1;
char name[50];
int count;
char gender;
} event[100];
int check(int code, int eventnum)
{
int i = 0;
if (code < 0 || code > 99)
{
printf("Invalid code entered.\n");
return 0;
}
while (i <= eventnum)
{
if (event[i].code == code)
{
printf("Event with code %d already exist\n", code);
return 0;
}
i++;
}
}
int checkcount(int count)
{
if (count < 10 || count > 99)
{
printf("Invalid number of player\n");
return 0;
}
}
int checkgender(char gender)
{
if (gender != 'M' && gender == 'F' && gender == 'X')
{
printf("Invalid gender\n");
return 0;
}
}
int main()
{
int eventnum = -1;
char choice;
int code, count, i, flag;
char gender;
while (1)
{
fflush(stdin);
printf("Enter operation code:");
scanf("%c", &choice);
switch (choice)
{
case 'i':
if (eventnum == 99)
{
printf("Input limit reached\n");
break;
}
printf("Enter the event code:");
scanf("%d", &code);
if (!check(code, eventnum + 1))
break;
printf("Enter event name:");
fflush(stdin);
fgets(event[eventnum + 1].name, 49, stdin);
fflush(stdin);
printf("Enter number of competiters:");
scanf("%d", &count);
if (!checkcount(count))
break;
fflush(stdin);
printf("Enter the gender:");
scanf("%c", &gender);
if (!checkgender(gender))
break;
fflush(stdin);
eventnum++;
event[eventnum].code = code;
event[eventnum].count = count;
event[eventnum].gender = gender;
break;
case 's':
i = 0;
flag = 0;
printf("Enter event code:");
scanf("%d", &code);
while (event[i].code != code)
{
i++;
}
if (event[i].code == code)
flag++;
if (flag == 0)
{
printf("Event with code %d not found.\n", code);
}
printf("CODE\tEVENT NAME\tCOMPETITORS\tGENDER\n");
printf("%d\t\t%s\t\t%d\t\t%c\n", event[i].code,
event[i].name, event[i].count, event[i].gender);
break;
case 'u':
i = 0;
flag = 0;
printf("Enter event code:");
scanf("%d", &code);
while (event[i].code != code)
{
i++;
}
if (event[i].code == code)
flag++;
if (flag == 0)
{
printf("Event with code %d not found.\n", code);
}
printf("Enter event name:");
fflush(stdin);
fgets(event[eventnum + 1].name, 49, stdin);
fflush(stdin);
printf("Enter Number of competitors:");
scanf("%d", &count);
if (!checkcount(count))
break;
fflush(stdin);
printf("Enter gender:");
scanf("%c", &gender);
fflush(stdin);
if (!checkgender(gender))
break;
event[i].count = count;
event[i].gender = gender;
break;
case 'p':
i = 0;
printf("CODE\tEVENT NAME\t\t\tCOMPETITORS\tGENDER\n");
while (i <= eventnum)
{
printf("%d\t%-49s\t%d\t\t%c\n",
event[i].code, event[i].name,
event[i].count, event[i].gender);
i++;
}
break;
case 'q':
exit(0);
default:
printf("Invalid input!\n");
}
}
return 0;
}
The critical issue is that the code is trying to define the event struct, but also somehow use it as a variable at the same time. C just doesn't work like that.
The code needs to first define what the structure is, and then secondly declare a variable that uses the definition.
Also it's not legal to define values for the structure to take inside the structure definition. This has to be done later. This is what is causing the error you see:
# gcc -g -Wall yourcode.c -o yourcode.exe
yourcode.c:5:11: error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘=’ token
int code = -1;
Perhaps you wanted something like:
struct event
{
int code;
char name[50];
int count;
char gender;
};
// Global array of event structs
#define MAX_EVENTS 100
struct event all_events[MAX_EVENTS];
// Initialise global events to "empty"
void initialiseEvents()
{
for (int i=0; i<MAX_EVENTS; i++)
{
all_events[i].code = -1;
all_events[i].name[0] = '\0';
all_events[i].count = 0;
all_events[i].gender = '-';
}
}
Here I've created a global variable all_events, which is an array of 100 struct event. This seems to to be the intention (I guess) of the existing code. I also added the function initialiseEvents() to loop through each event in all_events and set the values as per the original code (with a pinch of guesswork too).
Then the rest of the code keeps referring to the ill-defined "event" as if it's a variable, rather than a definition. Here you need to reference the variable using the type. Following my changes above, this would now be all_events.
Below is your code with these changes applied. Please compare it to your existing. It compiles OK, but I did not debug it further.
#include<stdio.h>
#include<stdlib.h>
struct event
{
int code;
char name[50];
int count;
char gender;
};
// Global array of event structs
#define MAX_EVENTS 100
struct event all_events[MAX_EVENTS];
int check(int code, int eventnum)
{
int i = 0;
if (code < 0 || code > 99)
{
printf("Invalid code entered.\n");
return 0;
}
while (i <= eventnum)
{
if (all_events[i].code == code)
{
printf("Event with code %d already exist\n", code);
return 0;
}
i++;
}
return 1;
}
int checkcount(int count)
{
if (count < 10 || count > 99)
{
printf("Invalid number of player\n");
return 0;
}
return 1;
}
int checkgender(char gender)
{
if (gender != 'M' && gender == 'F' && gender == 'X')
{
printf("Invalid gender\n");
return 0;
}
return 1;
}
// Initialise global events to "empty"
void initialiseEvents()
{
for (int i=0; i<MAX_EVENTS; i++)
{
all_events[i].code = -1;
all_events[i].name[0] = '\0';
all_events[i].count = 0;
all_events[i].gender = '-';
}
}
int main()
{
int eventnum = -1;
char choice;
int code, count, i, flag;
char gender;
initialiseEvents();
while (1)
{
fflush(stdin);
printf("Enter operation code:");
scanf("%c", &choice);
switch (choice)
{
case 'i':
if (eventnum == 99)
{
printf("Input limit reached\n");
break;
}
printf("Enter the event code:");
scanf("%d", &code);
if (!check(code, eventnum + 1))
break;
printf("Enter event name:");
fflush(stdin);
fgets(all_events[eventnum + 1].name, 49, stdin);
fflush(stdin);
printf("Enter number of competiters:");
scanf("%d", &count);
if (!checkcount(count))
break;
fflush(stdin);
printf("Enter the gender:");
scanf("%c", &gender);
if (!checkgender(gender))
break;
fflush(stdin);
eventnum++;
all_events[eventnum].code = code;
all_events[eventnum].count = count;
all_events[eventnum].gender = gender;
break;
case 's':
i = 0;
flag = 0;
printf("Enter event code:");
scanf("%d", &code);
while (all_events[i].code != code)
{
i++;
}
if (all_events[i].code == code)
flag++;
if (flag == 0)
{
printf("Event with code %d not found.\n", code);
}
printf("CODE\tEVENT NAME\tCOMPETITORS\tGENDER\n");
printf("%d\t\t%s\t\t%d\t\t%c\n", all_events[i].code,
all_events[i].name, all_events[i].count, all_events[i].gender);
break;
case 'u':
i = 0;
flag = 0;
printf("Enter event code:");
scanf("%d", &code);
while (all_events[i].code != code)
{
i++;
}
if (all_events[i].code == code)
flag++;
if (flag == 0)
{
printf("Event with code %d not found.\n", code);
}
printf("Enter event name:");
fflush(stdin);
fgets(all_events[eventnum + 1].name, 49, stdin);
fflush(stdin);
printf("Enter Number of competitors:");
scanf("%d", &count);
if (!checkcount(count))
break;
fflush(stdin);
printf("Enter gender:");
scanf("%c", &gender);
fflush(stdin);
if (!checkgender(gender))
break;
all_events[i].count = count;
all_events[i].gender = gender;
break;
case 'p':
i = 0;
printf("CODE\tEVENT NAME\t\t\tCOMPETITORS\tGENDER\n");
while (i <= eventnum)
{
printf("%d\t%-49s\t%d\t\t%c\n",
all_events[i].code, all_events[i].name,
all_events[i].count, all_events[i].gender);
i++;
}
break;
case 'q':
exit(0);
default:
printf("Invalid input!\n");
}
}
return 0;
}
#include <stdio.h>
#include <string.h>
struct birthdate {
int month, day, year;
};
typedef struct {
char fatherName[30];
char motherName[30];
} parentage;
typedef struct demigod {
char firstName[50];
char lastName[30];
int age;
parentage parents;
struct birthdate birthday;
} halfblood;
void addDemigod(struct demigod *camphalfblood, int i) {
printf("Enter name: ");
scanf("%s %s", camphalfblood[i].firstName, camphalfblood[i].lastName);
printf("Enter birth month: ");
scanf("%d", &camphalfblood[i].birthday.month);
printf("Enter birth day: ");
scanf("%d", &camphalfblood[i].birthday.day);
printf("Enter birth year: ");
scanf("%d", &camphalfblood[i].birthday.year);
camphalfblood[i].age = 2020 - camphalfblood[i].birthday.year;
printf("Enter mother's name: ");
scanf("%s", camphalfblood[i].parents.motherName);
printf("Enter father's name: ");
scanf("%s", camphalfblood[i].parents.fatherName);
}
void printAll (struct demigod *camphalfblood, int index) {
for (int i = 0; i < index; i++) {
printf("\nNAME : %s %s\n", camphalfblood[i].firstName, camphalfblood[i].lastName);
printf("BIRTHDAY: %d-%d-%d\n", camphalfblood[i].birthday.month, camphalfblood[i].birthday.day, camphalfblood[i].birthday.year);
printf("AGE: %d\n", camphalfblood[i].age);
printf("PARENTS: %s and %s\n\n", camphalfblood[i].parents.motherName, camphalfblood[i].parents.fatherName);
}
}
void editDemigod(struct demigod *camphalfblood, int index) {
int i;
for (i = 0; i < index; i++) {
printf("[%d] %s %s\n", i, camphalfblood[i].firstName, camphalfblood[i].lastName);
}
int choice;
printf("Enter index: ");
scanf("%d", &choice);
printf("Enter new first name: ");
scanf("%s", camphalfblood[choice].firstName);
printf("Enter new last name: ");
scanf("%s", camphalfblood[choice].lastName);
}
int main() {
struct demigod camphalfblood[20];
int choice;
int index = 0;
while (1) {
printf("[1] Add Demigod\n");
printf("[2] Print All Demigods\n");
printf("[3] Edit Demigod\n");
printf("[4] Exit\n");
printf("Enter choice: ");
scanf("%d", choice);
if (choice == 1) {
addDemigod(camphalfblood, index);
index++;
printf("Successfully added!\n");
} else if (choice == 2) {
printAll(camphalfblood, index);
} else if (choice == 3) {
editDemigod(camphalfblood, index);
} else if (choice == 4) {
break;
}
}
return 0;
}
Here's my code. There's no error when I compile it but the program somehow stops when after I entered the choice. I don't know where the error is. It just don't run and I don't know why. please help me, I really dont know what happened.
this is the output that I keep seeing, the program just stops there suddenly.
EDIT: I already got it, ampersands made me dumb wtf HAAAHAHAH
The error is here: scanf("%d", choice); has undefined behavior because you pass the value of choice instead of its address. This probably causes an invalid memory access resulting in program termination.
The solution is: scanf("%d", &choice)
Note that you should also check the return value of scanf() to detect invalid or missing input.
You should also pass the maximum number of characters for %s to avoid undefined behavior on user input longer than expected.
Here is a modified version of addDemigod() using helper functions:
int flushInput(void) {
int c;
while ((c = getchar()) != EOF && c != '\n')
continue;
return c;
}
int invalidInput(void) {
int res = 1;
printf("invalid input\n");
if (flushInput() == EOF) {
printf("unexpected end of file\n");
return 2;
} else {
return 1;
}
}
int addDemigod(struct demigod *camphalfblood, int i) {
printf("Enter name: ");
if (scanf("%49s %29s", camphalfblood[i].firstName, camphalfblood[i].lastName) != 2)
return invalidInput();
flushInput();
printf("Enter birth month: ");
if (scanf("%d", &camphalfblood[i].birthday.month) != 1)
return invalidInput();
flushInput();
printf("Enter birth day: ");
if (scanf("%d", &camphalfblood[i].birthday.day) != 1)
return invalidInput();
flushInput();
printf("Enter birth year: ");
if (scanf("%d", &camphalfblood[i].birthday.year) != 1)
return invalidInput();
camphalfblood[i].age = 2020 - camphalfblood[i].birthday.year;
flushInput();
printf("Enter mother's name: ");
if (scanf("%29s", camphalfblood[i].parents.motherName) != 1)
return invalidInput();
flushInput();
printf("Enter father's name: ");
if (scanf("%29s", camphalfblood[i].parents.fatherName) != 1)
return invalidInput();
flushInput();
return 0;
}
When I try to swap between strings in the function Update_student it doesn't make it. Why?
#include <stdio.h>
#include <string.h>
#define SIZE 1
struct student {
int id_number;
char name[50];
char sex[6];
int quiz_score[2];
int total_score;
};
void Add_Student_Records(struct student *pupil) {
printf("ID:");
scanf("%d", &pupil->id_number);
printf("Name: ");
scanf("%s", &pupil->name);
printf("Sex :");
scanf("%s", &pupil->sex);
for (int i = 0; i < 2; i++) {
printf("Quit score %d:", i + 1);
scanf("%d", &pupil->quiz_score[i]);
}
pupil->total_score = pupil->quiz_score[0] + pupil->quiz_score[1];
return;
}
void Add_Students(struct student *students) {
for (int i = 0; i < SIZE; i++) {
printf("Student %d:\n", i + 1);
Add_Student_Records(students);
}
return;
}
void Print_Students(struct student *students) {
for (int i = 0; i < SIZE; i++) {
printf("Student %d details: \n", i + 1);
printf("ID:%d\n", students->id_number);
printf("Name:%s\n", students->name);
printf("Sex:%s\n", students->sex);
for (int i = 0; i < 2; i++) {
printf("Quit score %d:\n", students->quiz_score[i]);
}
printf("Total score: %d\n", students->total_score);
students++;
}
return;
}
void Replace_Strings(char **old_string, char **new_string) {
*old_string = *new_string;
return;
}
void Update_Student(struct student *students) {
int i = 0;
char name[50], new_name[50], cur_name[50];
printf("You can update name, and scores.\n");
printf(" current Name: ");
scanf("%s", name);
printf("new name: ");
scanf("%s", &new_name);
while (i < SIZE) {
strcpy(cur_name, students->name);
if (strcmp(cur_name, name) == 0) {
char *ptr_old_stud_name = students->name;
char *ptr_new_stud_name = new_name;
Replace_Strings(&ptr_old_stud_name, &ptr_new_stud_name);
}
i++;
students++;
}
return;
}
int main() {
struct student students[SIZE];
char ch;
/*1.Add student, 2. Print student*/
printf("1.Add student\n2.Print students\n3.Update student\n");
scanf("%c", &ch);
while (ch != 'E') {
if (ch == '1') {
Add_Students(&students[0]);
}
else if (ch == '2') {
Print_Students(&students[0]);
}
else if (ch =='3') {
Update_Student(&students[0]);
}
printf("Another operation:\t");
scanf("%c", &ch);
}
}
Replace_Strings(&ptr_old_stud_name,&ptr_new_stud_name); passes the addresses of ptr_old_stud_name and ptr_new_stud_name to ReplaceStrings.
ptr_old_stud_name and ptr_new_stud_name are local variables. The first is a pointer that has been set to point to students->name. The second is a pointer that has been set to point to new_name.
Replace_Strings changes the first thing it is passed a pointer to to the second thing it is passed a pointer to. So it changes ptr_old_stud_name to have the value of ptr_new_stud_name.
The result is that the local variable ptr_old_stud_name has a new value. This does not change the thing it points to, students->name.
More specifically, ptr_old_stud_name was pointing to the first character of students->name. students->name is an array, and it cannot be altered by changing pointers to it, and its address cannot be changed. To change its contents, you must copy new values into the bytes within it, which you could do by using strcpy to copy bytes into it from new_name.
Your function Update_student is confusing, you should just iterate through the array of students and compare the student's name with cur_name and replace the name when there is a match.
You should also pass the number of students to handle as an argument.
Here is a modified version:
void Update_Student(struct student *students, int count) {
char cur_name[50], new_name[50];
printf("You can update name, and scores.\n");
printf(" current Name: ");
scanf("%49s", cur_name);
printf("new name: ");
scanf("%49s", new_name);
for (int i = 0; i < count; i++) {
if (strcmp(cur_name, students[i].name) == 0) {
strcpy(students[i].name, new_name);
}
}
}
Call from main as Update_Student(students, SIZE);
Note also that you should ignore whitespace when reading the commands by adding a space before the %c:
scanf(" %c", &ch);
Here is a modified version with for multiple students:
#include <stdio.h>
#include <string.h>
#define SIZE 10
struct student {
int id_number;
char name[50];
char sex[6];
int quiz_score[2];
int total_score;
};
int Add_Student_Records(struct student *pupil) {
printf("ID:");
if (scanf("%d", &pupil->id_number) != 1)
return 0;
printf("Name: ");
if (scanf("%49s", pupil->name) != 1)
return 0;
printf("Sex :");
if (scanf("%1s", pupil->sex) != 1)
return 0;
for (int i = 0; i < 2; i++) {
printf("Quiz score %d:", i + 1);
if (scanf("%d", &pupil->quiz_score[i]) != 1)
return 0;
}
pupil->total_score = pupil->quiz_score[0] + pupil->quiz_score[1];
return 1;
}
int Add_Students(struct student *students, int count) {
int i;
for (int i = 0; i < count; i++) {
printf("Student %d:\n", i + 1);
if (Add_Student_Records(students + i) == 0)
break;
}
return i;
}
void Print_Students(struct student *students, int count) {
for (int i = 0; i < count; i++) {
printf("Student %d details: \n", i + 1);
printf("ID:%d\n", students->id_number);
printf("Name:%s\n", students->name);
printf("Sex:%s\n", students->sex);
for (int i = 0; i < 2; i++) {
printf("Quit score %d:\n", students->quiz_score[i]);
}
printf("Total score: %d\n", students->total_score);
students++;
}
}
void Update_Student(struct student *students, int count) {
char cur_name[50], new_name[50];
printf("You can update name, and scores.\n");
printf(" current Name: ");
if (scanf("%49s", cur_name) != 1)
return;
printf("new name: ");
if (scanf("%49s", new_name) != 1)
return;
for (int i = 0; i < count; i++) {
if (strcmp(cur_name, students[i].name) == 0) {
strcpy(students[i].name, new_name);
}
}
}
int main() {
struct student students[SIZE];
int n = 0;
char ch = 'E';
/* print the menu */
printf("1. Add student\n"
"2. Print students\n"
"3. Update student\n");
scanf(" %c", &ch);
while (ch != 'E') {
if (ch == '1') {
if (n == SIZE) {
printf("student array is full\n");
} else {
/* add more students */
n += Add_Students(&students[n], SIZE - n);
}
} else
if (ch == '2') {
Print_Students(students, n);
} else
if (ch =='3') {
Update_Student(students, n);
}
scanf("%*[^\n]"); // consume the rest of the pending input line
printf("Another operation:\t");
if (scanf(" %c", &ch) != 1)
break;
}
return 0;
}
Repeat the Program for again Search Array Element.
#include <stdio.h>
#define MAX_SIZE 100
int main()
{
int arr[MAX_SIZE];
int size, i, toSearch, found;
char repeat;
printf("Enter the size of an array\n");
scanf("%d", &size);
printf("Enter the array elements\n");
for (i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}
do{
printf("\nEnter element to search: ");
scanf("%d", &toSearch);
found = 0;
for(i=0; i<size; i++)
{
if(arr[i] == toSearch)
{
found = 1;
break;
}
}
if(found == 1)
{
printf("\n%d is found at position %d", toSearch, i + 1);
}
else
{
printf("\n%d is not found in the array \n", toSearch);
}
printf("\n \n \nPress Y to again Search Any Element in Array\n \nPress Any other Key to Exit the Program\n\n");
scanf(" %c \t",&repeat);
}
while(repeat == 'y' || repeat == 'Y' );
return 0;
}
I want to repeat my program when user give the input of Y || y otherwise it'll exit the program.
In this code i want to make an array then search the element after this show's the results and in last repeat the code from the search the element block.
I ran your code and everything seems to be working properly except for this line:
scanf(" %c \t",&repeat);
Remove the \t from the scanf and it should work properly. You don't want to scan for a tab character, just the 'Y' or 'y' character.
Also, your use of newlines is a bit unusual. Try putting newline characters at the end of your strings as opposed to the beginning.
Updated code:
#include <stdio.h>
#define MAX_SIZE 100
int main() {
int arr[MAX_SIZE];
int size, i, toSearch, found;
char repeat = ' ';
printf("Enter the size of an array\n");
scanf("%d", &size);
printf("Enter the array elements\n");
for (i = 0; i < size; i++)
scanf("%d", &arr[i]);
do{
printf("Enter element to search: \n");
scanf("%d", &toSearch);
found = 0;
for(i=0; i<size; i++) {
if(arr[i] == toSearch) {
found = 1;
break;
}
}
if(found == 1)
printf("%d is found at position %d\n", toSearch, i + 1);
else printf("%d is not found in the array\n", toSearch);
printf("Press Y to again Search Any Element in Array\nPress Any other Key to Exit the Program\n");
scanf(" %c",&repeat);
}
while(repeat == 'y' || repeat == 'Y' );
return 0;
}
Enclose the block of code you want to repeat in a while loop, something like
bool flag = false;
while(flag==true) {
//Code block
scanf("%c",&input)
if((input == 'y') || (input == 'Y')) {flag = true;}
else {flag = false;}
}
The first method that came to my mind :
#include <stdio.h>
#define MAX_SIZE 100
int main()
{
int arr[MAX_SIZE];
int size, i, toSearch, found;
char repeat;
printf("Enter the size of an array\n");
scanf("%d", &size);
printf("Enter the array elements\n");
for (i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}
do
{
printf("\nEnter element to search: ");
scanf("%d", &toSearch);
found = 0;
for (i = 0; i < size; i++)
{
if (arr[i] == toSearch)
{
found = 1;
break;
}
}
if (found == 1)
{
printf("\n%d is found at position %d", toSearch, i + 1);
}
else
{
printf("\n%d is not found in the array \n", toSearch);
}
printf("\n \n \nPress Y to again Search Any Element in Array\n \nPress Any other Key to Exit the Program\n\n");
repeat = getchar();
repeat = getchar();
if(repeat == 'y' || repeat == 'Y') {
continue;
}
else {
break;
}
} while (1);
return 0;
}
I have a problem to display my input to my program. Can someone help me to solve my problem?
I want my program look like this. But it is confusing when my program just display one name when I put more than one name and number
#pragma warning (disable:4996)
#include<stdio.h>
#include<string.h>
#include<ctype.h>
#include<stdlib.h>
struct contact {
char name[30];
char number[12];
};
int main() {
int menu;
struct contact contact;
int flag, flag_1, flag_2, flag_3;
int i;
start:
printf("Phone Book\n");
printf("==========\n");
printf("1. Add New Contact\n");
printf("2. View List Contact\n");
printf("3. Search Contact\n");
printf("4. Delete Contact\n");
printf("5. Exit\n");
printf("choose menu: ");
scanf("%d", &menu); fflush(stdin);
system("cls");
switch (menu) {
case 1: printf("Add New Contact\n\n");
do {
flag = flag_1 = 1;
printf("input name [1..30 char]: ");
scanf(" %[^\n]", contact.name);
if (!isalpha(contact.name[0])) {
flag = 0;
printf("First letter of name should be an alphabet (A-Z or a-z)\n");
}
if (strlen(contact.name) > 30) {
flag_1 = 0;
printf("Length of name should be between 1 and 30 characters\n");
}
} while (flag == 0 || flag_1 == 0);
do {
flag_2 = flag_3 = 1;
printf("Input phone number[6..12 digits]: ");
scanf(" %[^\n]", contact.number);
for (i = 0; i < strlen(contact.number); i++) {
if (!isdigit(contact.number[i])) {
flag_2 = 0;
}
}
if (flag_2 == 0) {
printf("Phone numbers should only contain digits (0-9)\n");
}
if (strlen(contact.number) < 6 || strlen(contact.number) > 12) {
flag_3 = 0;
printf("Length of phone numbers should be between 6 and 12 digits\n");
}
} while (flag_2 == 0 || flag_3 == 0);
printf("\n");
printf("New contact successfully added!\n\n");
printf("Name : %s \nNumber : %s\n\n", contact.name, contact.number);
printf("Press Enter to continue...");
getchar();
getchar();
system("cls");
goto start;
case 2:
char c;
int i;
printf("View List Contact\n\n");
printf(" # Name Phone Number\n");
for (c = 'A'; c <= 'Z'; c++) {
for (i = 1; ; i++) {
if (c == contact.name[0]) {
printf("%c %d. %s %s", c, i, contact.name, contact.number);
}
break;
}
}
getchar();
}
getchar();
return 0;
}
Currently, you only create one variable of contact with name and number elements (both char arrays). This is why you can only record one contact.
To make it right, firstly, you need to create a contact array and to have a variable to trace the number of contacts you currently are having:
struct contact {
char name[30];
char number[12];
};
int main() {
int menu;
struct contact contacts[30]; //add this
int flag, flag_1, flag_2, flag_3;
int i;
char c;
int noOfContact = 0; //add this
Then, for case 1, you should point to the contact in your contacts array you want to create based on index given by noOfContact like this
case 1: printf("Add New Contact\n\n");
do {
flag = flag_1 = 1;
printf("input name [1..30 char]: ");
scanf(" %[^\n]", contacts[noOfContact].name); //notice the noOfContact index is used
if (!isalpha(contacts[noOfContact].name[0])) {
flag = 0;
printf("First letter of name should be an alphabet (A-Z or a-z)\n");
}
if (strlen(contacts[noOfContact].name) > 30) {
flag_1 = 0;
printf("Length of name should be between 1 and 30 characters\n");
}
} while (flag == 0 || flag_1 == 0);
do {
flag_2 = flag_3 = 1;
printf("Input phone number[6..12 digits]: ");
scanf(" %[^\n]", contacts[noOfContact].number);
for (i = 0; i < strlen(contacts[noOfContact].number); i++) {
if (!isdigit(contacts[noOfContact].number[i])) {
flag_2 = 0;
}
}
if (flag_2 == 0) {
printf("Phone numbers should only contain digits (0-9)\n");
}
if (strlen(contacts[noOfContact].number) < 6 || strlen(contacts[noOfContact].number) > 12) {
flag_3 = 0;
printf("Length of phone numbers should be between 6 and 12 digits\n");
}
} while (flag_2 == 0 || flag_3 == 0);
printf("\n");
printf("New contact successfully added!\n\n");
printf("Name : %s \nNumber : %s\n\n", contacts[noOfContact].name, contacts[noOfContact].number);
printf("Press Enter to continue...");
noOfContact++;
getchar();
getchar();
system("cls");
goto start;
Similarly, in your case 2, you should create iteration from 0 to noOfContact to display you contact one by one, something like this.
case 2:
printf("View List Contact\n\n");
printf(" # Name Phone Number\n");
for (i = 0; i < noOfContact; ++i)
printf("%c %d. %s %s\n", c, i, contacts[i].name, contacts[i].number);
getchar();
}
The keys are the contact array and the noOfContact
You must use an array of struct contacts, or allocate dynamic using linked list; now you are overwriting the contact.