C program query - c

So this is my program and the number, name, address doesn't print again after single execution and also If the seat is already taken there should be "seat is taken already, please try again" which I'm confused about
#include <stdio.h>
#include <stdlib.h>
int main()
{
struct passenger
{
char name[20];
char address[30];
int age;
};
struct passenger data;
struct rwcl
{
int row;
char col;
};
int clmn, i, j;
int arr[5][5];
struct rwcl number;
for(i=0;i<5;i++)
{
printf("Enter Your Name: ");
scanf("\n");
gets(data.name);
printf("Enter Your Address: ");
scanf("\n");
gets(data.address);
printf("Enter Your Age: ");
scanf("%d", &data.age);
printf("\nAll aboard! You may now choose your desired seat/s.");
while(i<5){
for(j=0;j<5;j++){
if (j == 0) {
arr[i][j] = i+1;
}
if(j == 1){
arr[i][j] = 'A';
}
if(j== 2){
arr[i][j] = 'B';
}
if(j == 3){
arr[i][j] = 'C';
}
if(j== 4){
arr[i][j] = 'D';
}
}
i++;
}
printrwcl:
printf("\n\n");
for(i=0;i<5;i++){
for(j=0;j<5;++j){
if(j == 0 ){
printf("%-5d", arr[i][j]);
}
else {
printf("%-5c", arr[i][j]);
}
}
if(j==5) {
printf("\n");
}
}
printf("\n");
rowselect:
printf("Choose a row between 1,2,3,4,5 or 6 for cancellation: ");
scanf("%d", &number.row);
if(number.row < 0 || number.row > 6) {
printf("\nPlease, re-enter. Thank you.\n");
goto rowselect;
}
if(number.row == 6) {
printf("Recorded, thank you.");
exit(0);
}
columnselect:
printf("Choose a letter between A,B,C,D: ");
scanf("\n");
scanf("%c", &number.col);
switch(number.col)
{
case 'A':
clmn = 1;
break;
case 'B':
clmn = 2;
break;
case 'C':
clmn = 3;
break;
case 'D':
clmn = 4;
break;
}
if(arr[number.row-1][clmn] == 'X')
{
printf("Seat is taken. Please choose a different one.");
}
else
{
printf("Seat %d%c has been reserved.", number.row, number.col);
arr[number.row-1][clmn] = 'X';
}
goto printrwcl;
}
}

Related

String input scanf for struct

This is the question consisting of 1st stage, 2nd stage and 3rd stage.
This is the code for 1st stage and it works well.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#pragma warning(disable:4996)
struct PERSON {
char name[20];
char phoneNumber[15];
char birthDate[8];
};
struct PERSON record[100];
int personCount = 0;
char nameValidation(char name[]) {
rewind(stdin);
scanf("%s", name);
for (int i = 0; i < strlen(name); i++) {
if (strlen(name) > 20) {
printf("Name must be less than 20 characters. Please try again\n");
printf("Name: ");
rewind(stdin);
return nameValidation(name);
}
if ((name[i] < 'a' || name[i] > 'z') && (name[i] < 'A' || name[i] > 'Z')) {
printf("Invalid name. Please try again.\n");
printf("Name: ");
rewind(stdin);
return nameValidation(name);
}
}
return *name;
}
char phoneNumValidation(char phoneNumber[]) {
rewind(stdin);
scanf("%s", phoneNumber);
for (int i = 0; i < strlen(phoneNumber); i++) {
if (strlen(phoneNumber) > 15) {
printf("Phone number must be less than 15 characters. Please try again\n");
printf("Phone number: ");
rewind(stdin);
return phoneNumValidation(phoneNumber);
}
if (phoneNumber[i] < '0' || phoneNumber[i] > '9') {
printf("Invalid phone number. Please try again.\n");
printf("Phone number: ");
rewind(stdin);
return phoneNumValidation(phoneNumber);
}
}
return *phoneNumber;
}
char birthDateValidation(char birthDate[]) {
rewind(stdin);
scanf("%s", birthDate);
for (int i = 0; i < strlen(birthDate); i++) {
if (strlen(birthDate) > 8) {
printf("Birth date must be less than 8 characters. Please try again\n");
printf("Birth date: ");
rewind(stdin);
return birthDateValidation(birthDate);
}
if (birthDate[i] < '0' || birthDate[i] > '9') {
printf("Invalid birth date. Please try again.\n");
printf("Birth date: ");
rewind(stdin);
return birthDateValidation(birthDate);
}
}
return *birthDate;
}
int choiceValidation(char statement[], int min, int max) {
int choice;
printf("%s", statement);
rewind(stdin);
scanf("%d", &choice);
if (choice < min || choice > max) {
printf("Invalid choice. Please try again.\n");
return choiceValidation(statement, min, max);
}
return choice;
}
void registration() {
printf("Name: ");
nameValidation(record[personCount].name);
printf("Phone_number: ");
phoneNumValidation(record[personCount].phoneNumber);
printf("Birth: ");
birthDateValidation(record[personCount].birthDate);
personCount++;
printf("<<%d>>\n", personCount);
}
void showAll() {
for (int i = 0; i < personCount; i++) {
printf("%s %s %s\n", record[i].name, record[i].phoneNumber, record[i].birthDate);
}
}
void deleteFunction() {
char name[20];
printf("Name: ");
nameValidation(name);
for (int i = 0; i < personCount; i++) {
if (strcmp(name, record[i].name) == 0) {
for (int j = i; j < personCount; j++) {
strcpy(record[j].name, record[j + 1].name);
strcpy(record[j].phoneNumber, record[j + 1].phoneNumber);
strcpy(record[j].birthDate, record[j + 1].birthDate);
}
personCount--;
return;
}
}
}
void findByBirth() {
char birthMonth[3], getBirthMonth[3];
int position = 5, length = 2, check = 0;
printf("Birth month: ");
birthDateValidation(birthMonth);
for (int i = 0; i < personCount; i++) {
while (check < length) {
getBirthMonth[check] = record[i].birthDate[position + check - 1];
check++;
}
if (strncmp(birthMonth, getBirthMonth, 2) == 0) {
printf("%s %s %s\n", record[i].name, record[i].phoneNumber, record[i].birthDate);
}
}
}
int main() {
int menuNum;
do {
printf("*****Menu*****\n");
printf("<1.Registration><2.ShowAll><3.Delete><4.FindByBirth><5.Exit>\n");
menuNum = choiceValidation("Enter the menu number: ", 1, 5);
switch (menuNum) {
case 1:registration(); break;
case 2:showAll(); break;
case 3:deleteFunction(); break;
case 4:findByBirth(); break;
case 5:exit(-1); break;
}
} while (menuNum != 5);
return 0;
}
And this is the code for 2nd stage where I modified according to the question but I encountered error.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#pragma warning(disable:4996)
struct PERSON {
char *name;
char *phoneNumber;
char *birthDate;
};
struct PERSON **record;
int personCount = 0;
char nameValidation(char name[]) {
rewind(stdin);
scanf("%s", name);
for (int i = 0; i < strlen(name); i++) {
if (strlen(name) > 20) {
printf("Name must be less than 20 characters. Please try again\n");
printf("Name: ");
rewind(stdin);
return nameValidation(name);
}
if ((name[i] < 'a' || name[i] > 'z') && (name[i] < 'A' || name[i] > 'Z')) {
printf("Invalid name. Please try again.\n");
printf("Name: ");
rewind(stdin);
return nameValidation(name);
}
}
return *name;
}
char phoneNumValidation(char phoneNumber[]) {
rewind(stdin);
scanf("%s", phoneNumber);
for (int i = 0; i < strlen(phoneNumber); i++) {
if (strlen(phoneNumber) > 15) {
printf("Phone number must be less than 15 characters. Please try again\n");
printf("Phone number: ");
rewind(stdin);
return phoneNumValidation(phoneNumber);
}
if (phoneNumber[i] < '0' || phoneNumber[i] > '9') {
printf("Invalid phone number. Please try again.\n");
printf("Phone number: ");
rewind(stdin);
return phoneNumValidation(phoneNumber);
}
}
return *phoneNumber;
}
char birthDateValidation(char birthDate[]) {
rewind(stdin);
scanf("%s", birthDate);
for (int i = 0; i < strlen(birthDate); i++) {
if (strlen(birthDate) > 8) {
printf("Birth date must be less than 8 characters. Please try again\n");
printf("Birth date: ");
rewind(stdin);
return birthDateValidation(birthDate);
}
if (birthDate[i] < '0' || birthDate[i] > '9') {
printf("Invalid birth date. Please try again.\n");
printf("Birth date: ");
rewind(stdin);
return birthDateValidation(birthDate);
}
}
return *birthDate;
}
int choiceValidation(char statement[], int min, int max) {
int choice;
printf("%s", statement);
rewind(stdin);
scanf("%d", &choice);
if (choice < min || choice > max) {
printf("Invalid choice. Please try again.\n");
return choiceValidation(statement, min, max);
}
return choice;
}
void registration() {
printf("Name: ");
nameValidation(record[personCount].name);
printf("Phone_number: ");
phoneNumValidation(record[personCount].phoneNumber);
printf("Birth: ");
birthDateValidation(record[personCount].birthDate);
personCount++;
printf("<<%d>>\n", personCount);
}
void showAll() {
for (int i = 0; i < personCount; i++) {
printf("%s %s %s\n", record[i].name, record[i].phoneNumber, record[i].birthDate);
}
}
void deleteFunction() {
char name[20];
printf("Name: ");
nameValidation(name);
for (int i = 0; i < personCount; i++) {
if (strcmp(name, record[i].name) == 0) {
for (int j = i; j < personCount; j++) {
strcpy(record[j].name, record[j + 1].name);
strcpy(record[j].phoneNumber, record[j + 1].phoneNumber);
strcpy(record[j].birthDate, record[j + 1].birthDate);
}
personCount--;
return;
}
}
}
void findByBirth() {
char birthMonth[3], getBirthMonth[3];
int position = 5, length = 2, check = 0;
printf("Birth month: ");
birthDateValidation(birthMonth);
for (int i = 0; i < personCount; i++) {
while (check < length) {
getBirthMonth[check] = record[i].birthDate[position + check - 1];
check++;
}
if (strncmp(birthMonth, getBirthMonth, 2) == 0) {
printf("%s %s %s\n", record[i].name, record[i].phoneNumber, record[i].birthDate);
}
}
}
int main() {
int menuNum;
printf("Max_num: ");
scanf("%d", &max_num);
do {
printf("*****Menu*****\n");
printf("<1.Registration><2.ShowAll><3.Delete><4.FindByBirth><5.Exit>\n");
menuNum = choiceValidation("Enter the menu number: ", 1, 5);
switch (menuNum) {
case 1:
if(personCount < n)
{
registration(n);
personCount++;
break;
}
else
{
printf("OVERFLOW\n");
break;
}
case 2:showAll(); break;
case 3:deleteFunction(); break;
case 4:findByBirth(); break;
case 5:exit(-1); break;
}
} while (menuNum != 5);
return 0;
}
I received error messages when compiling, so I follow the error messages where I need to change all the . to ->.
And it can be compiled and run.
I manage to input max_num and menuNum.
When I input menuNum 1 (void registration), I try to input the name, but the program stops immediately.
Where did I go wrong?
This is the code after I change all the . to ->
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#pragma warning(disable:4996)
struct PERSON {
char *name;
char *phoneNumber;
char *birthDate;
};
struct PERSON **record;
int personCount = 0;
char nameValidation(char name[]) {
rewind(stdin);
scanf("%s", name);
for (int i = 0; i < strlen(name); i++) {
if (strlen(name) > 20) {
printf("Name must be less than 20 characters. Please try again\n");
printf("Name: ");
rewind(stdin);
return nameValidation(name);
}
if ((name[i] < 'a' || name[i] > 'z') && (name[i] < 'A' || name[i] > 'Z')) {
printf("Invalid name. Please try again.\n");
printf("Name: ");
rewind(stdin);
return nameValidation(name);
}
}
return *name;
}
char phoneNumValidation(char phoneNumber[]) {
rewind(stdin);
scanf("%s", phoneNumber);
for (int i = 0; i < strlen(phoneNumber); i++) {
if (strlen(phoneNumber) > 15) {
printf("Phone number must be less than 15 characters. Please try again\n");
printf("Phone number: ");
rewind(stdin);
return phoneNumValidation(phoneNumber);
}
if (phoneNumber[i] < '0' || phoneNumber[i] > '9') {
printf("Invalid phone number. Please try again.\n");
printf("Phone number: ");
rewind(stdin);
return phoneNumValidation(phoneNumber);
}
}
return *phoneNumber;
}
char birthDateValidation(char birthDate[]) {
rewind(stdin);
scanf("%s", birthDate);
for (int i = 0; i < strlen(birthDate); i++) {
if (strlen(birthDate) > 8) {
printf("Birth date must be less than 8 characters. Please try again\n");
printf("Birth date: ");
rewind(stdin);
return birthDateValidation(birthDate);
}
if (birthDate[i] < '0' || birthDate[i] > '9') {
printf("Invalid birth date. Please try again.\n");
printf("Birth date: ");
rewind(stdin);
return birthDateValidation(birthDate);
}
}
return *birthDate;
}
int choiceValidation(char statement[], int min, int max) {
int choice;
printf("%s", statement);
rewind(stdin);
scanf("%d", &choice);
if (choice < min || choice > max) {
printf("Invalid choice. Please try again.\n");
return choiceValidation(statement, min, max);
}
return choice;
}
void registration() {
printf("Name: ");
nameValidation(record[personCount]->name);
printf("Phone_number: ");
phoneNumValidation(record[personCount]->phoneNumber);
printf("Birth: ");
birthDateValidation(record[personCount]->birthDate);
personCount++;
printf("<<%d>>\n", personCount);
}
void showAll() {
for (int i = 0; i < personCount; i++) {
printf("%s %s %s\n", record[i]->name, record[i]->phoneNumber, record[i]->birthDate);
}
}
void deleteFunction() {
char name[20];
printf("Name: ");
nameValidation(name);
for (int i = 0; i < personCount; i++) {
if (strcmp(name, record[i]->name) == 0) {
for (int j = i; j < personCount; j++) {
strcpy(record[j]->name, record[j + 1]->name);
strcpy(record[j]->phoneNumber, record[j + 1]->phoneNumber);
strcpy(record[j]->birthDate, record[j + 1]->birthDate);
}
personCount--;
return;
}
}
}
void findByBirth() {
char birthMonth[3], getBirthMonth[3];
int position = 5, length = 2, check = 0;
printf("Birth month: ");
birthDateValidation(birthMonth);
for (int i = 0; i < personCount; i++) {
while (check < length) {
getBirthMonth[check] = record[i]->birthDate[position + check - 1];
check++;
}
if (strncmp(birthMonth, getBirthMonth, 2) == 0) {
printf("%s %s %s\n", record[i]->name, record[i]->phoneNumber, record[i]->birthDate);
}
}
}
int main() {
int menuNum, max_num;
printf("Max_num: ");
scanf("%d", &max_num);
do {
printf("*****Menu*****\n");
printf("<1.Registration><2.ShowAll><3.Delete><4.FindByBirth><5.Exit>\n");
menuNum = choiceValidation("Enter the menu number: ", 1, 5);
switch (menuNum) {
case 1:
if(personCount < max_num)
{
registration();
personCount++;
break;
}
else
{
printf("OVERFLOW\n");
break;
}
case 2:showAll(); break;
case 3:deleteFunction(); break;
case 4:findByBirth(); break;
case 5:exit(-1); break;
}
} while (menuNum != 5);
return 0;
}
Latest code I edit using suggestion by #itati.
I manage to input name, phone number and birthdate. But I can only input once even though I set the max_num to 3, and the program stops immediately after input birthdate.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#pragma warning(disable:4996)
struct PERSON {
char *name;
char *phoneNumber;
char *birthDate;
};
struct PERSON **record;
int personCount = 0;
char nameValidation(char name[]) {
rewind(stdin);
scanf("%s", name);
for (int i = 0; i < strlen(name); i++) {
if (strlen(name) > 20) {
printf("Name must be less than 20 characters. Please try again\n");
printf("Name: ");
rewind(stdin);
return nameValidation(name);
}
if ((name[i] < 'a' || name[i] > 'z') && (name[i] < 'A' || name[i] > 'Z')) {
printf("Invalid name. Please try again.\n");
printf("Name: ");
rewind(stdin);
return nameValidation(name);
}
}
return *name;
}
char phoneNumValidation(char phoneNumber[]) {
rewind(stdin);
scanf("%s", phoneNumber);
for (int i = 0; i < strlen(phoneNumber); i++) {
if (strlen(phoneNumber) > 15) {
printf("Phone number must be less than 15 characters. Please try again\n");
printf("Phone number: ");
rewind(stdin);
return phoneNumValidation(phoneNumber);
}
if (phoneNumber[i] < '0' || phoneNumber[i] > '9') {
printf("Invalid phone number. Please try again.\n");
printf("Phone number: ");
rewind(stdin);
return phoneNumValidation(phoneNumber);
}
}
return *phoneNumber;
}
char birthDateValidation(char birthDate[]) {
rewind(stdin);
scanf("%s", birthDate);
for (int i = 0; i < strlen(birthDate); i++) {
if (strlen(birthDate) > 8) {
printf("Birth date must be less than 8 characters. Please try again\n");
printf("Birth date: ");
rewind(stdin);
return birthDateValidation(birthDate);
}
if (birthDate[i] < '0' || birthDate[i] > '9') {
printf("Invalid birth date. Please try again.\n");
printf("Birth date: ");
rewind(stdin);
return birthDateValidation(birthDate);
}
}
return *birthDate;
}
int choiceValidation(char statement[], int min, int max) {
int choice;
printf("%s", statement);
rewind(stdin);
scanf("%d", &choice);
if (choice < min || choice > max) {
printf("Invalid choice. Please try again.\n");
return choiceValidation(statement, min, max);
}
return choice;
}
void registration(int max_num) {
record = (struct PERSON**) malloc(max_num* sizeof(struct PERSON**));
while (true){
printf("Name: ");
nameValidation(record[personCount]->name);
printf("Phone_number: ");
phoneNumValidation(record[personCount]->phoneNumber);
printf("Birth: ");
birthDateValidation(record[personCount]->birthDate);
personCount++;
printf("<<%d>>\n", personCount);
}
}
void showAll() {
for (int i = 0; i < personCount; i++) {
//printf("%s %s %s\n", record[i].name, record[i].phoneNumber, record[i].birthDate);
printf("%s %s %s\n", record[i]->name, record[i]->phoneNumber, record[i]->birthDate);
}
}
void deleteFunction() {
char name[20];
printf("Name: ");
nameValidation(name);
for (int i = 0; i < personCount; i++) {
//if (strcmp(name, record[i].name) == 0) {
if (strcmp(name, record[i]->name) == 0) {
for (int j = i; j < personCount; j++) {
//strcpy(record[j].name, record[j + 1].name);
//strcpy(record[j].phoneNumber, record[j + 1].phoneNumber);
//strcpy(record[j].birthDate, record[j + 1].birthDate);
strcpy(record[j]->name, record[j + 1]->name);
strcpy(record[j]->phoneNumber, record[j + 1]->phoneNumber);
strcpy(record[j]->birthDate, record[j + 1]->birthDate);
}
personCount--;
return;
}
}
}
void findByBirth() {
char birthMonth[3], getBirthMonth[3];
int position = 5, length = 2, check = 0;
printf("Birth month: ");
birthDateValidation(birthMonth);
for (int i = 0; i < personCount; i++) {
while (check < length) {
//getBirthMonth[check] = record[i].birthDate[position + check - 1];
getBirthMonth[check] = record[i]->birthDate[position + check - 1];
check++;
}
if (strncmp(birthMonth, getBirthMonth, 2) == 0) {
//printf("%s %s %s\n", record[i].name, record[i].phoneNumber, record[i].birthDate);
printf("%s %s %s\n", record[i]->name, record[i]->phoneNumber, record[i]->birthDate);
}
}
}
int main() {
int menuNum, max_num;
printf("Max_num: ");
scanf("%d", &max_num);
do {
printf("*****Menu*****\n");
printf("<1.Registration><2.ShowAll><3.Delete><4.FindByBirth><5.Exit>\n");
menuNum = choiceValidation("Enter the menu number: ", 1, 5);
switch (menuNum) {
case 1:
if(personCount < max_num)
{
registration(max_num);
personCount++;
break;
}
else
{
printf("OVERFLOW\n");
break;
}
case 2:showAll(); break;
case 3:deleteFunction(); break;
case 4:findByBirth(); break;
case 5:exit(-1); break;
}
} while (menuNum != 5);
return 0;
}
I don't know why you need to use flush and PERSON**.
According to the problem, maybe you wrote "loop" in the wrong place.
I rewrite a code, it should be ok.
void registration(int n)
{
record = (struct PERSON*) malloc(n* sizeof(struct PERSON*));
while (true){
printf("Name: ");
scanf("%s", record[personCount]->name);
printf("Phone Number: ");
scanf("%s", record[personCount]->phoneNumber);
personCount++;
printf("<<%d>>\n", personCount);
}
}

Search function in CRUD with C

I'm making a contact book in C and I've already done the parts of registering contact, listing all contacts and deleting a contact, but I need to elaborate the part of searching the contact, and also searching contacts that start with a given string, but I'm not succeeding... I'll leave my code below to see if anyone can help me identify where I'm going wrong:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LENGTH 50
typedef struct
{
char name[MAX_LENGTH];
char number[MAX_LENGTH];
int bd;
char bdm[MAX_LENGTH];
} ContactBook;
void ListContacts(ContactBook **c, int quant)
{
int i;
printf("\n List of contacts: \n");
for (i = 0; i < quant; i++)
{
printf("\t%d = birthday: %2d month %s\t name: %s \t number: %s\n", i + 1, c[i]->bd, c[i]->bdm, c[i]->name, c[i]->number);
}
}
int addContacts(ContactBook **c, int quant, int size)
{
if (quant < size)
{
ContactBook *new = malloc(sizeof(ContactBook));
printf("\nenter contact name: ");
scanf("%s", new->name);
printf("\nenter number: ");
scanf("%s", new->number);
printf("\nenter the birthday ");
scanf("%d", &new->bd);
printf("\n enter the month birthday: ");
scanf("%s", new->bdm);
c[quant] = new;
return 1;
}
else
{
printf("\n full list.\n");
return 0;
}
}
int deleteContact(ContactBook **c, int quant)
{
int id;
ListContacts(c, quant);
printf("\n\t Enter the id you want to delete: \n");
scanf("%d", &id);
getchar();
id--;
if (id >= 0 && id < quant)
{
free(c[id]);
if (id < quant - 1)
{
c[id] = c[quant - 1];
}
return -1;
}
else
{
printf("\n\t wrong code;\n");
return 0;
}
}
void SearchContact(ContactBook **c, int quant)
{
int i;
char searchedName[30];
for (i = 0; i < quant; i++)
{
printf("\n Search name: \n");
scanf("%s", searchedName);
getchar();
if (strcmp(searchedName, c[i]->name) == 0)
{
printf("the name: %s was found", c[i]->name);
}
else
{
printf("name not found");
}
}
}
int main()
{
ContactBook *contacts[50];
int option, size = 50, quant = 0;
do
{
printf(" \n\t0 - exit\n\t1 - register contact\n\t2 - Remove contact\n\t3- List contacts\n\t4- Search contact\n\t");
scanf("%d", &option);
getchar();
switch (option)
{
case 1:
quant += addContacts(contacts, quant, size);
break;
case 2:
quant += deleteContact(contacts, quant);
break;
case 3:
ListContacts(contacts, quant);
break;
case 4:
SearchContact(contacts, quant);
break;
}
} while (option != 0);
return 0;
}

Can't get my C program to print the output

When I go to print the output of the program everything shows up as zero. I think the variable aren't storing themselves, but I'm not totally sure. When I go to look over everything, it looks right but clearly isn't. Any help would be really appreciated. Sorry if the formatting seems a little off, Stack Overflow wouldn't accept it otherwise.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int digit(char term[])
{
int i = 0;
int val = 0;
while (term[i] != '\0')
{
val = val * 10 + term[i] - '0';
}
i++;
return val;
}
void error()
{
printf("Error: Sales figures must be numbers.\n");
printf("Please try again.\n");
}
bool isnumber(char term[])
{
int i = 0;
while (term[i])
{
if( isdigit(term[i]) == 0)
{
return false;
i++;
}
}
return true;
}
int main()
{
int sales[3][2], costs[3] = {3, 4, 1}, weekends[2] = {0, 0};
int i, j, val;
char term[100];
while (1)
{
printf("Number of Bagel sales on Saturday: ");
scanf("%s", term);
if( isnumber(term) == false)
{
error();
}
else
{
sales[0][0] = digit(term);
break;
}
}
while (1)
{
printf("Number of Flatbread sales on Saturday: ");
scanf("%s", term);
if( isnumber(term) == false)
{
error();
}
else
{
sales[1][0] = digit(term);
break;
}
}
while (1)
{
printf("Number of Muffin sales on Saturday: ");
scanf("%s", term);
if (isnumber(term) == false)
{
error();
}
else
{
sales[2][0] = digit(term);
break;
}
}
while (1)
{
printf("Number of Bagel sales on Sunday: ");
scanf("%s", term);
if( isnumber(term) == false)
{
error();
}
else
{
sales[0][1] = digit(term);
break;
}
}
while (1)
{
printf("Number of Flatbread sales on Sunday: ");
scanf("%s", term);
if( isnumber(term) == false)
{
error();
}
else
{
sales[1][1] = digit(term);
break;
}
}
while (1)
{
printf("Number of Muffin sales on Sunday: ");
scanf("%s", term);
if( isnumber(term) == false)
{
error();
}
else
{
sales[2][1] = digit(term);
break;
}
}
for (i = 0; i < 2, i++;)
{
for (j = 0; j < 3, j++;)
{
weekends[i] += costs[j] * sales[i][j];
}
}
printf("\n");
for (i = 0; i < 3, i++;)
{
printf("%d", costs[i]);
}
printf(".");
for (i = 0; i < 3, i++;)
{
for (j = 0; j < 2, j++;)
{
printf("%d", sales[i][j]);
}
if (i == 0)
{
printf(" = ");
printf("%d %d", weekends[0], weekends[1]);
}
printf("\n ");
}
printf("\nTotal sales on Saturday: $%d", weekends[0]);
printf("\nTotal sales on Sunday: $%d", weekends[1]);
printf("\nTotal sales over the weekend: $%d", weekends[0] + weekends[1]);
return 0;
}
You are not incrementing i in the loop. Your code for digit is:
int digit(char term[])
{
int i = 0;
int val = 0;
while (term[i] != '\0')
{
val = val * 10 + term[i] - '0';
}
i++; /* ---- this is outside the loop !! */
return val;
}
But it ought to look like:
int
digit(const char *term)
{
int val = 0;
while( *term != '\0' ){
val = val * 10 + *term - '0';
term += 1;
}
return val;
}

How to properly make a dynamic command-line menu?

More precisely.. How do I add a "go back to main menu" function as all other softwares and games have?
void showMenu()
{
puts( "1. Create school\n"
"2. Add room\n"
"3.Add student to room\n"
"4.Find student\n"
"5. Show students in room\n"
"\n" "6. Exit");
}
int main()
{
clrscr();
studentList *foundStudent;
int input;
showMenu();
while( scanf("%d", &input) )
{
if(input == 6)
{
periods("Exiting");
break;
}
if(input == 1)
{
school *school;
school = createSchool();
}
if(input == 2)
{
int room, roomNr;
printf("Enter room Nr. and Class:");
scanf("%d %d", &room, &roomNr);
}
}
return 0;
}
Anything I attempted didn't work and just created more redundancy, never expected how goto can be so confusing.
Although switch makes more sense, I don't believe it fixes my problem.
Here is a working example.
The solution for this problem was simply making a "menu within a menu" kind of, I did use some gotos but as far as commandline menu goes, this may be all.
#define clrscr() printf("\e[1;1H\e[2J")
void periods(char* message)
{
const int trigger = 500; // ms
const int numDots = 3;
while (1)
{
// Return and clear with spaces, then return and print prompt.
printf("\r%*s\r%s", sizeof(message) - 1 + numDots, "", message);
fflush(stdout);
// Print numDots number of dots, one every trigger milliseconds.
for (int i = 0; i < numDots; i++)
{
usleep(trigger * 1000);
fputc('.', stdout);
fflush(stdout);
}
break;
}
}
void showmenu()
{
clrscr();
puts("1. New Game\n"
"2. Load Game\n"
"3. Credits\n\n"
"4. Exit\n" );
}
int checkString(char *str)
{
int status = 0;
int ln = strlen(str);
for(int i = 0; i < ln; i++)
{
if(isdigit( str[i] ) )
status = 1;
break;
}
return status;
}
int main(){
char choice;
clrscr();
int status, isNum = -101;
char *name, *buffer, YN;
showmenu();
while(1)
{
scanf(" %c", &choice);
if( isdigit(choice) )
{
break;
}
else
{
fflush(stdin);
printf("Please only enter numbers!\n");
sleep(1);
showmenu();
}
}
do{
switch(choice)
{
case '1':
{
createG:;
clrscr();
printf("Enter name or press 0 to return\n");
scanf("%s", buffer);
status = checkString(buffer);
if(status == 1)
{
clrscr();
break;
}
clrscr();
name = (char*)malloc(strlen(buffer)+1);
strcpy(name, buffer);
printf("New game created, welocome %s!\n");
for(int i = 0; i < 5; i++)
{
sleep(1);
printf("%d\n", i);
}
break;
}
case '2':
{
int what;
caseL:;
clrscr();
printf("No saves!\n Create new game? [Y/N] \n to return press 0\n");
scanf(" %c", &YN);
if(YN == 'N') what = 0;
if(YN == '0') what = -1;
if(YN == 'Y') what = 1;
switch(YN)
{
case 'N':
{
goto caseL;
}
case '0':
{
break;
}
case 'Y':
{
choice = 1;
goto createG;
break;
}
}
break;
}
case '3':
{
periods("Hello World");
break;
}
case '4':
{
clrscr();
periods("Goodbye");
clrscr();
exit(1);
}
default:
{
printf("Wrong input\n Try again");
sleep(1);
break;
}
}
}while(choice != -2);
return 0;
}
This may still need a lot of error checking and handling for "unexpected" inputs but it answers the problem.

Why `system("cls")` works only if it is called by a certain function?

I am developing a simple hotel reservation management system, but I've encountered a little problem. The system("cls"); in mainMenu() function doesn't work, only if the mainMenu() function is called by the bookRoom() function. I tried works just fine with other function, I have no idea why this happens.
Where is my mistake?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <windows.h>
char exitOpt[1],cfm[1];;
int mainMenu_Opt;
int chk = 0;
int advance[4] = {750, 500, 250, 125};
int roomFee[4] = {1500, 1000, 500 ,250};
int rT[4] = {1,2,3,4};
int roomAvail[4] = {1,2,2,5};
struct guest{
char id[5];
char name[30];
int age;
int r_type;
int chk_in_date;
int chk_out_date;
int per;
int totPay;
int paid;
int balance;
};
struct guest grec;
FILE *fguest,*ftemp;
void main();
void mainMenu();
void checkRoom();
void putRAV();
int bookRoom();
void vldRT();
void readData();
void exitProgram ();
void mainMenu()
{
system("cls");
for(;;)
{
fguest = fopen("guest_list.dat","rb");
while(fread(&grec,sizeof(grec),1,fguest)==1 )
{
if (grec.r_type == chk)
roomAvail[chk-1]--;
}
chk = 0;
fclose(fguest);
printf("\n Welcome to HRMS \n\n");
printf("\tMain Menu\n\n");
printf("1. Check Room's Availability\n\n");
printf("2. Book A Room\n\n");
printf("3. Check Out a Room Guest\n\n");
printf("4. Edit Reservation\n\n");
printf("5. Search\n\n");
printf("6. Exit\n\n");
printf("Please, enter your choice (1-6): ");
scanf("%d",&mainMenu_Opt);
fflush(stdin);
switch(mainMenu_Opt)
{
case 1: { putRAV();
break; }
case 2: {
bookRoom();
break; }
// case 3: { chkoRoom();
// break; }
//
// case 4: { editRes();
// break; }
//
case 5: { readData();
break; }
case 6: { exitProgram();
break; }
default: printf("\nInvalid Input. Please try again with valid input (whole number between 1 - 6).\n ");
}
}
}
void checkRoom()
{
system("cls");
fguest = fopen("guest_list.dat","rb");
while(fread(&grec,sizeof(grec),1,fguest)==1 )
{
switch (grec.r_type)
{
case 1: {
roomAvail[0]--;
break; }
case 2: {
roomAvail[1]--;
break; }
case 3: {
roomAvail[2]--;
break; }
case 4: {
roomAvail[3]--;
break; }
}
}
fclose(fguest);
}
void putRAV()
{
system("cls");
int j;
for (j = 0; j < 4; j++)
{
printf("%d\n", roomAvail[j]);
}
printf("Back to main (Y/N)?: "); gets(cfm); fflush(stdin);
if ((strcmp(cfm,"Y")==0) || (strcmp(cfm,"y")==0))
{ printf("Returning to main menu...\n");
Sleep(1000);
mainMenu(); }
else if ((strcmp(cfm,"N")==0) || (strcmp(cfm,"n")==0))
{ putRAV(); }
else
{ printf("\nInvalid Input. Returning to ReadData\n");
putRAV(); }
}
int bookRoom()
{
system("cls");
fflush(stdin);
grec.totPay = 0;
fguest = fopen("guest_list.dat","ab+");
printf("\n\tBook A Room");
printf("\n\nGuest\'s ID\t\t: "); scanf("%s",grec.id); fflush(stdin);
printf("Guest\'s Name\t\t: "); scanf("%30s",grec.name); fflush(stdin);
printf("Guest\'s Age\t\t: "); scanf("%d",&grec.age); fflush(stdin);
printf("Room\'s Type\t\t: "); scanf("%d",&grec.r_type); fflush(stdin);
vldRT();
printf("Check-in Date\t\t: "); scanf("%d",&grec.chk_in_date); fflush(stdin);
printf("Check-out Date\t\t: "); scanf("%d",&grec.chk_out_date); fflush(stdin);
printf("Staying Period\t\t: "); scanf("%d",&grec.per); fflush(stdin);
grec.totPay = (roomFee[grec.r_type - 1] * grec.per) - advance[grec.r_type-1];
printf("Total Payment\t\t: %d\n", grec.totPay);
printf("Total Paid\t\t: "); scanf("%d",&grec.paid); fflush(stdin);
grec.balance = grec.totPay - grec.paid;
printf("Balance\t\t\t: %d \n\n",grec.balance);
printf("\t\t Confirm Booking (Y/N)?: "); gets(cfm); fflush(stdin);
if ((strcmp(cfm,"Y")==0) || (strcmp(cfm,"y")==0))
{ fwrite(&grec,sizeof(grec),1,fguest);
fclose(fguest);
chk = grec.r_type;
printf("Room successfully booked...\n");
printf("Returning to main menu...\n");
Sleep(1000);
return chk;
}
else if ((strcmp(cfm,"N")==0) || (strcmp(cfm,"n")==0))
{ bookRoom(); }
else
{ printf("\nInvalid Input. Returning to Book A Room\n");
bookRoom(); }
mainMenu();
}
void vldRT()
{
if (grec.r_type <= 0 || grec.r_type >4)
{
printf("Invalid input!! Input must be between 1 - 4\n");
printf("Please try again:\n");
printf("Room\'s Type\t\t: "); scanf("%d",&grec.r_type); fflush(stdin); }
}
void exitProgram ()
{
printf("\nExit program (Y/N)? "); gets(exitOpt); fflush(stdin);
if ((strcmp(exitOpt,"Y")==0) || (strcmp(exitOpt,"y")==0))
exit(0);
else if ((strcmp(exitOpt,"N")==0) || (strcmp(exitOpt,"n")==0))
mainMenu();
else
printf("\nInvalid Input. Please try again with valid input (Y/N). \n");
exitProgram();
}
void readData()
{
system("cls");
fguest = fopen("guest_list.dat","rb");
rewind(fguest);
while(fread(&grec,sizeof(grec),1,fguest)==1) //continue reading until there's no more struct data
{
printf("\n\nGuest\'s ID\t\t: %s", grec.id);
printf("\nGuest\'s Name\t\t: %s",grec.name);
printf("\nGuest\'s Age\t\t: %d",grec.age);
printf("\nRoom\'s Type\t\t: %d",grec.r_type);
printf("\nCheck-in Date\t\t: %d",grec.chk_in_date);
printf("\nCheck-out Date\t\t: %d",grec.chk_out_date);
printf("\nStaying Period\t\t: %d",grec.per);
printf("\nTotal Payment\t\t: %d", grec.totPay);
printf("\nTotal Paid\t\t: %d",grec.paid);
printf("\nBalance\t\t\t: %d \n\n",grec.balance);
}
fclose(fguest);
printf("Back to main (Y/N)?: "); gets(cfm); fflush(stdin);
if ((strcmp(cfm,"Y")==0) || (strcmp(cfm,"y")==0))
{ printf("Returning to main menu...\n");
Sleep(1000);
mainMenu(); }
else if ((strcmp(cfm,"N")==0) || (strcmp(cfm,"n")==0))
{ readData(); }
else
{ printf("\nInvalid Input. Returning to ReadData\n");
readData(); }
}
void main()
{
checkRoom();
mainMenu();
}
Why not make your own cls function that is portable?
void my_cls(void) {
int i = 5000;
while (i-->0)
printf("\n");
}

Resources