String input scanf for struct - c

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);
}
}

Related

Get first letter from C string

I have a program in C which is basically a contact book, and I've already done all the functionalities (add contact, delete etc) but I also have to implement a way to search for contacts by the initial letter (the user type any letter, and if they exist contacts that start with that letter they should be displayed) but I'm not getting the first letter of the vector of names to do this... My attempt to do this is in the SearchContactsByFirstLetter function...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <locale.h>
#include <time.h>
#define MAX_LENGTH 50
typedef struct
{
char name[MAX_LENGTH];
char number[MAX_LENGTH];
int bd;
int bdm;
} ContactBook;
void ListContacts(ContactBook **c, int quant)
{
int i;
printf("\n List of contacts: \n");
printf("\t---------------------\n");
for (i = 0; i < quant; i++)
{
printf("\t%d = birthday: %2d month %2d\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("%49[^\n]", new->name);
printf("\nenter number: ");
scanf("%s", new->number);
printf("\nenter the birthday ");
scanf("%d", &new->bd);
printf("\n enter the month birthday: ");
scanf("%d", &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);
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 birthdays(ContactBook **c, int quant)
{
int i;
time_t t = time(NULL);
struct tm tm = *localtime(&t);
printf(" os aniversariantes do mês são: \n");
for (i = 0; i < quant; i++)
{
if (tm.tm_mon + 1 == c[i]->bdm)
{
printf("\t%d = birthday: %2d month %2d\t name: %s \t number: %s\n", i + 1, c[i]->bd, c[i]->bdm, c[i]->name, c[i]->number);
}
}
}
void SearchContactByFirstLetter(ContactBook **c, int quant)
{
int i;
char searchedName[2];
printf("\n Search a letter: \n");
scanf("%s", searchedName);
getchar();
for (i = 0; i < quant; i++)
{
if (strcmp(searchedName, c[i]->name[0]) == 0)
{
printf("\t\nname: %s, \nnumber: %s, \nbirthday: %d \nmonth birthday %d \t\n", c[i]->name, c[i]->number, c[i]->bd, c[i]->bdm);
}
}
}
void SearchContact(ContactBook **c, int quant)
{
int i;
char searchedName[30];
printf("\n Search name: \n");
scanf("%s", searchedName);
getchar();
for (i = 0; i < quant; i++)
{
if (strcmp(searchedName, c[i]->name) == 0)
{
printf("\t\nname: %s, \nnumber: %s, \nbirthday: %d \nmonth birthday %d \t\n", c[i]->name, c[i]->number, c[i]->bd, c[i]->bdm);
}
}
}
void saveBinary(char arquivo[], ContactBook **c, int quant)
{
FILE *file = fopen(arquivo, "wb");
int i;
if (file)
{
for (i = 0; i < quant; i++)
fwrite(c[i], sizeof(ContactBook), 1, file);
fclose(file);
}
else
printf("erro");
}
int readBinaryArq(char arquivo[], ContactBook **c)
{
int quant = 0;
ContactBook *new = malloc(sizeof(ContactBook));
FILE *file = fopen(arquivo, "rb");
if (file)
{
while (fread(new, sizeof(ContactBook), 1, file))
{
c[quant] = new;
quant++;
new = malloc(sizeof(ContactBook));
}
fclose(file);
}
else
printf("\nerro");
return quant;
}
int main()
{
ContactBook *contacts[50];
int option, size = 50, quant = 0;
char arq2[] = ("agenda.dat");
quant = readBinaryArq(arq2, contacts);
do
{
printf(" \n\t0 - exit\n\t1 - register contact\n\t2 - Remove contact\n\t3- List contacts\n\t4- Search contact\n\t5 - ver aniversariantes do mês\n\t6-Pesquisar por inicial\n ");
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;
case 5:
birthdays(contacts, quant);
break;
}
saveBinary(arq2, contacts, quant);
} while (option != 0);
return 0;
}
if (strcmp(searchedName, c[i]->name[0]) == 0)
That should be:
if (searchedName[0] == c[i]->name[0])
But you probably shouldn't read in a string in the first place if you only want to read a single character.

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;
}

C program query

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;
}
}

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;
}

I have got a problem with reading binary file into array of structures in c

Here is part of my code:
Here I want to transfer already saved .bin file into a new database structure student s, but it is not transferring more than one member of a structure.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char name[20];
int date;
int month;
int year;
int id;
int pnum;
}student;
int count = 0;
void swap(student* s1, student* s2) {
student* temp;
temp = s1;
s1 = s2;
s2 = temp;
}
void sort(student* s) {
for (int i = 0; i < count - 1; i++) {
for (int j = i + 1; j < count; j++) {
if (strcmp((s + i)->name, (s + j)->name) > 0) {
student temp = *(s + i);
*(s + i) = *(s + j);
*(s + j) = temp;
}
}
}
}
void addInf(student* s) {
printf("\t==================================Adding information=====================================\n\n");
printf("\t\tPlease input following information: \n");
printf("\tName: ");
scanf("%s", (s + count)->name);
printf("\tDate of birth (yyyymmdd): ");
scanf("%4d%2d%2d", &(s + count)->year, &(s + count)->month, &(s + count)->date);
printf("\tStudent ID: ");
scanf("%d", &(s + count)->id);
printf("\tPhone number: ");
scanf("%d", &(s + count)->pnum);
count++;
printf("\tEntry succeded.\n");
printf("\t=========================================================================================\n\n");
}
void print(student* s) {
printf("\t\tName: %s\n", s->name);
printf("\t\tBidthday: %d/%02d/%02d\n", s->year, s->month, s->date);
printf("\t\tID: %d\n", s->id);
printf("\t\tPhone number: %d\n", s->pnum);
}
void delInf(student* s, int n) {
int com;
printf("\t=================================Deleting information====================================\n\n");
printf("\t=========================================================================================\n\n");
char name[20];
printf("\t\tPlease input name of the student that you want to delete: ");
scanf("%s", &name);
for (int i = 0; i < count; i++) {
if ((strcmp(name, (s + i)->name)) == 0) {
printf("\t\tInformation that you want to delete\n");
print((s + i));
for (int j = i; j < count; j++) {
*(s + i) = *(s + i + 1);
count--;
printf("\t\tInformation was succesfully deleted.\n\n");
}
}
}
}
void searchByID(student* s) {
int key;
printf("\t======================================Searching by ID====================================\n\n");
printf("\t\tEnter ID: ");
scanf("%d", &key);
printf("\t=========================================================================================\n\n");
int i;
for (i = 0; i < count; i++) {
if (key == (s + i)->id) {
break;
}
}
print((s + i));
}
void searchByName(student* s) {
char key[20];
int i;
int size, check = 0;
printf("\t======================================Searching by Name==================================\n\n");
printf("\t\tEnter Name: ");
scanf("%s", &key);
printf("\t=========================================================================================\n\n");
for (i = 0; i < count; i++) {
if (strcmp(key, (s + i)->name) == 0) {
print((s + i));
}
}
}
void searchByBirthDate(student* s) {
int key, command;
int i;
printf("\t================================Searching by Birthdate================================\n\n");
printf("\t\t1.By Date\t\t 2.By Month\t\t 3.By Year\t\t 4.By All\n");
printf("\t\tCommand: ");
scanf("%d", &command);
printf("\t=========================================================================================\n\n");
if (command == 1) {
printf("Enter date: ");
scanf("%2d", &key);
printf("\t\tStudent with same date\n");
for (i = 0; i < count; i++) {
if (key == (s + i)->date) {
printf("\t\t---------%d----------\n\n", i + 1);
print((s + i));
}
}
}
if (command == 2) {
printf("\t\tEnter month: ");
scanf("%2d", &key);
printf("\t\tStudent with same month\n");
for (i = 0; i < count; i++) {
if (key == (s + i)->month) {
printf("\t\t---------%d----------\n\n", i + 1);
print((s + i));
}
}
}
if (command == 3) {
printf("\t\tEnter year: ");
scanf("%4d", &key);
printf("\t\tStudent with same year\n");
for (i = 0; i < count; i++) {
if (key == (s + i)->year) {
printf("\t\t---------%d----------\n\n", i + 1);
print(s + i);
}
}
}
if (command == 4) {
int yy, mm, dd;
printf("\t\tEnter birthdate: ");
scanf("%4d%2d%2d", &yy, &mm, &dd);
for (i = 0; i < count; i++) {
if (yy == (s + i)->year && mm == (s + i)->month && dd == (s + i)->date) {
break;
}
}
print(s + i);
}
}
void printTable(student* s) {
printf("\t============================================Table========================================\n\n");
printf("\t\tName\t\t\tBirthday\t\t\tStudent ID\t\t\tPhone number\n\n");
for (int i = 0; i < count; i++) {
printf("\t%d. %s\t\t\t\t%d/%d/%d\t\t\t%d\t\t\t0%d\n\n", i + 1, (s + i)->name, (s + i)->year, (s + i)->month, (s + i)->date, (s + i)->id, (s + i)->pnum);
}
printf("\t=========================================================================================\n\n");
}
void search(student* s) {
printf("\t=========================================Search==========================================\n\n");
printf("\t\tAvailable commands: \n");
printf("\t\t1. Search by name\t\t\t2. Search by ID\n\t\t3. Search by birthday\n");
printf("\t=========================================================================================\n\n");
printf("\t\tPlease choose command: ");
int com;
scanf("%d", &com);
switch (com) {
case 1: searchByName(s);
break;
case 2: searchByID(s);
break;
case 3: searchByBirthDate(s);
break;
}
}
void menu() {
printf("\n\t======================================MENU===============================================\n");
printf("\t\tAvailable commands: \n");
printf("\t\t1. Add Student\t\t\t2.Delete student\n\t\t3. Find student\t\t\t4. Table of all students\n");
printf("\t\t5. Transfer information from binary file\n\t\t6. Save information into binary file.\n\t\t0. Exit\n\n");
printf("\t=========================================================================================\n\n");
printf("\t\tPlease choose command: ");
}
int main() {
FILE* fp;
FILE* fpr;
printf("\t\tEnter a name of binary file that you want to create: ");
char filename[20];
scanf("%s", &filename);
strcat(filename, ".bin");
fp = fopen(filename, "ab");
if (fp == NULL) {
printf("\t\tUnable to open the file.\nError\n");
exit(1);
}
else printf("\t\t\tFile %s successfuly created\n\n", filename);
int iCount;
int n, c;
student* s;
printf("\t\tPlease enter number of students: ");
scanf("%d", &n);
printf("\n\n");
s = (student*)calloc(n, sizeof(student));
int quit = 1;
while (quit) {
menu();
scanf("%d", &c);
printf("\n");
switch (c) {
case 0:
quit = 0;
break;
case 1:
addInf(&s);
break;
case 2:
delInf(&s, n);
break;
case 3:
search(&s);
break;
case 4:
if (count == 0) printf("\t\tThere is no any given information yet.\n\n");
else printTable(&s);
break;
case 5:
printf("\t\tEnter a name or path of file that you want to open: ");
char readfilename[30];
scanf("%s", &readfilename);
strcat(readfilename, ".bin");
fpr = fopen(readfilename, "rb+");
if (fpr == NULL) {
printf("\t\tUnable to open the file.\nError\n");
break;
}
else printf("\t\tFile %s successfuly opened for reading\n", readfilename);
printf("\t\t\ttransfering binary data from %s into database\n", readfilename);
while ((fread(&s, sizeof(student), 1, fpr)) == 1) {
count++;
}
printf("\t\t%d student information was successfuly transferred\n", count);
break;
case 6:
iCount = fwrite(&s, sizeof(student), count, fp);
if (iCount != count) printf("Information could be missed in %s file\n", filename);
else printf("\t\tAll information was successfuly copied into %s file", filename);
}
sort(&s);
}
fclose(fp);
return 0;
}
First of all, enable warnings when compiling, and follow up on them!
This should tell you that &s is wrong in every place where you used it.
This causes your program to suffer from undefined behavior, which is a total pest when trying to debug your program!
Now then, on to the code that reads students from file:
while ((fread(s, sizeof(student), 1, fpr)) == 1) {
count++;
}
Every student is read into the same memory area (pointed to by s). They overwrite each other, leaving only the last one read. Try s + count instead of s:
while ((fread(s + count, sizeof(student), 1, fpr)) == 1) {
count++;
}

Resources