I'm making a program where I'm entering an activity hours for dogs and then sums the hour for each activity and after that the program print each dog one after another from the dog with higher sum of hours of activites to the lowest
now I did sort the list and made a print function , but still doesn't work , it prints either 2 of them if the first dog I entered has the highest sum of hours and the seconde is the lowers in the right order, but if there first dog was the one with the lowest and the seconde one was the one with the highest it just prints the first dog ( the loswet one) and doesn't even print the seconde dog.
input:
2
any1
6
6
6
any2
3
3
3
Actual output:
any1 6 6 6
Expected output:
any2 3 3 3
any1 6 6 6
My code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_LENGTH 30
#define GRADE 100.0
#define AVG_SLEEP 12
#define AVG_WALK 1.25
#define AVG_PLAY 2
#define TEN 10.0
#define EIGHT 8.0
typedef struct dog* dogPtr;
typedef struct dog
{
char name[MAX_NAME_LENGTH]; /*30*/
double sleep;
double walk;
double playtime;
dogPtr next;
} Dog;
double calculateGrade (dogPtr dog);
void addDog(dogPtr* fitBarkList);
void printDogList(dogPtr fitBarkList);
void freeList (dogPtr list);
int main()
{
int amount_of_dogs;
int i;
dogPtr list = NULL;
printf("Welcome to FitBarkList\n");
printf("Enter the amount of dogs: \n");
if(!scanf("%d", &amount_of_dogs))
{
printf("Input Error\n");
return 0;
}
while (amount_of_dogs <1)
{
printf("Enter the amount of dogs: \n");
if(!scanf("%d",&amount_of_dogs))
{
printf("Input Error\n");
return 0;
}
}
for(i = 0; i < amount_of_dogs; i++)
{
printf("Enter dog number %d\n", i+1 );
addDog(&list);
}
printDogList(list);
freeList(list);
return 0;
}
/**this function frees the allocated memory*/
void freeList (dogPtr list)
{
if(list != NULL)
{
freeList(list->next);
free(list);
}
}
void addDog(dogPtr* fitBarkList)
{
dogPtr tmp=*fitBarkList,tmp2=NULL,curr;
dogPtr p = (dogPtr)malloc(sizeof(Dog));
if(p == NULL )
{
printf("allocation failed\n");
exit(1);
}
printf("Enter the dog's name: \n");
scanf("%s", p->name);
printf("Enter the dog's average sleeping time: \n");
scanf("%lf", &p->sleep);
printf("Enter the dog's average walking time: \n");
scanf("%lf", &p->walk);
printf("Enter the dog's average play time: \n");
scanf("%lf", &p->playtime);
p->next=NULL;
if (*fitBarkList == NULL)
{
*fitBarkList=p;
return ;
}
curr=p;
while (tmp!=NULL)
{
if (calculateGrade(curr) < calculateGrade (tmp))
{
tmp2=tmp;
tmp=tmp->next;
}
else
{
return ;
}
}
if (tmp != NULL)
{
curr=tmp2->next;
tmp->next=curr;
}
if (tmp == NULL)
{
tmp2->next=curr;
curr->next=NULL;
}
}
/**this function prints the grade of the dog then shows the total grade*/
void printDogList(dogPtr fitBarkList)
{
dogPtr curr=fitBarkList;
if(curr == NULL)
{
return ;
}
while(curr!=NULL)
{
printf("%s \n", curr->name);
printf("Sleeping grade %.2f \n", curr->sleep);
printf("Play time grade: %.2f \n", curr->playtime);
printf("Walking grade: %.2f \n", curr->walk);
printf("Total grade: %.2f \n", calculateGrade(curr));
curr=curr->next;
}
}
/**this function to calculate the grades for each activity*/
double calculateGrade(dogPtr dog)
{
double sleep = dog->sleep,
walk = dog->walk,
playtime = dog->playtime;
if (sleep == 12.0)
sleep = GRADE;
else if (sleep < AVG_SLEEP)
sleep = GRADE - ((12.0 - sleep) * TEN);
else if (sleep > AVG_SLEEP)
sleep = GRADE - ((sleep - AVG_SLEEP) * TEN);
if (walk == AVG_WALK&& walk>=0.25)
walk = GRADE;
else if (walk > AVG_WALK )
walk = GRADE - ((walk - AVG_WALK) * EIGHT);
else if (sleep <= 0.25)
walk = GRADE - GRADE;
else if (walk < AVG_WALK && walk > 0.25)
walk = GRADE - ((AVG_WALK - walk) * GRADE);
if (playtime == AVG_PLAY)
playtime = GRADE;
else if (playtime > AVG_PLAY)
playtime = GRADE - ((playtime - AVG_PLAY) * EIGHT);
else if (playtime < AVG_PLAY)
playtime = GRADE - 60.0;
else if (AVG_PLAY>playtime && playtime>1.0)
playtime=GRADE-(GRADE*(AVG_PLAY-playtime));
return sleep + walk + playtime;
}
When you find the new place where to insert the new dog, you walk the list if there is a next dog and if the new dog's grade is below the current dog's grade. (I've renamed the two iterators curr and prev for clarity.)
When you insert the new dog, p, the next dog is the current dog, p->next = curr. If the current dog's grade is the smallest of if the list was empty, curr is NULL, which is fine. You don't need to treat an empty list as special case.
Now, if prev == NULL, your new dog ist the current best. There is no previous node, so update the head pointer via *fitBarkList. Otherwise, update the next field of the previous node:
dogPtr p = create_node(...); // alloc and read stuff
dogPtr curr = *fitBarkList; // p goes before this ...
dogPtr prev = NULL; // ... and after this
while (curr && calculateGrade(p) < calculateGrade (curr)) {
prev = curr;
curr = curr->next;
}
p->next = curr;
if (prev == NULL) { // first node
*fitBarkList = p;
} else { // subsequent nodes
prev->next = p;
}
Related
I have the code below and it is supposed to print the names I have given but instead it prints blank spaces.
I might've made a mistake with data type's because I was printing integers but not names. I couldn't figure it out.
Here's the full code but I think the main problem is at printStack function.
Edit: I've changed everything to english sorry for the confusion.
#include <stdio.h>
#include <stdlib.h>
#define SIZE 25
char stack[SIZE];
int top=-1;
int isFull(){
if (top>=SIZE-1){
return 1;
}
return 0;
}
struct n{
n * next;
char data;
};
typedef n node;
void printStack(char person){
printf("Entered persons: \n");
for(int i=0;i<=top;i++)
printf("%c\n",stack[person]);
printf("\n");
}
void push(node * root, char person){
if(root == NULL || isFull()){
root = (node *)malloc(sizeof(node));
root -> data = person;
root -> next = NULL;
stack[++top]=person;
}
node * iter = root;
while(iter->next !=NULL || isFull()){
iter = iter -> next;
stack[++top]=person;
}
}
int main()
{
int pick;
char person;
node * s=NULL;
while (1){
printf("1 - Add person\n");
printf("2 - Show persons\n");
printf("3 - Exit\n");
scanf("%d",&pick);
switch (pick){
case 1:
printf ("Person name: ");
scanf("%s",&person);
push(s, person);
break;
case 2:
printStack(person);
break;
case 3:
exit(0);
break;
}
}
return 0;
}
printStack() iterates over stack but in the printf() call you print stack[yolcu] so the same thing top + 1 times. I think you mean to print stack[i]. There is a logic error between 1 and later elements (first element top is 1 after 2nd element top is 3). I suggest you use the normal c range [0; top[ where top is now size instead of a (possible invalid) index so initialize is to 0 instead of -1. Iterate i<top. Full if top >= BOYUT. You want to use scanf(" %c", ..) to ignore the newline from previous prompt:
#include <stdio.h>
#include <stdlib.h>
#define BOYUT 25
char stack[BOYUT];
int top=0;
int isFull(){
return top >= BOYUT;
}
typedef struct node {
struct node *next;
char data;
} node;
void printStack(){
printf("Girilen yolcular: \n");
for(int i=0;i<top;i++)
printf("%i: %c\n",i, stack[i]);
printf("\n");
}
void push(node * root, char yolcu){
if(root == NULL || isFull()){
root = malloc(sizeof(node));
root -> data = yolcu;
root -> next = NULL;
stack[top++]=yolcu;
}
node * iter = root;
while(iter->next !=NULL || isFull()){
iter = iter -> next;
stack[top++]=yolcu;
}
}
int main() {
int secim;
char yolcu;
node *s=NULL;
while (1){
printf("1 - Yolcu Ekleme\n");
printf("2 - Yolculari Goster\n");
printf("3 - Cikis\n");
scanf("%d",&secim);
switch (secim){
case 1:
printf ("Yolcu Adi: ");
scanf(" %c",&yolcu);
push(s, yolcu);
printf("\n");
break;
case 2:
printStack();
break;
case 3:
return 0;
break;
}
}
}
and example session:
1 - Yolcu Ekleme
2 - Yolculari Goster
3 - Cikis
1
Yolcu Adi: a
1 - Yolcu Ekleme
2 - Yolculari Goster
3 - Cikis
1
Yolcu Adi: b
1 - Yolcu Ekleme
2 - Yolculari Goster
3 - Cikis
2
Girilen yolcular:
0: a
1: b
1 - Yolcu Ekleme
2 - Yolculari Goster
3 - Cikis
I'm trying to write a program that reads a maximum of 8 bank account information and store them dynamically in a linked list. I wrote a function to calculate the average of all the entered bank accounts' balances but when I try to call that function no output is produced. can you please help me figure out where the problem is?
#include <stdio.h>
#include <stdlib.h>
//node structure
typedef struct node {
int no;
char name[20];
float total;
struct node * nextptr;
}
account;
//int for division of total to find the average
static int t;
//adding accounts function
account * addaccount(account * temp) {
fflush(stdin);
printf("Enter the account name: \n");
gets(temp -> name);
printf("Enter the account number: \n");
scanf("%d", & temp -> no);
printf("Enter the account balance: \n");
scanf("%f", & temp -> total);
t++; // used for finding the average
return temp;
}
// function for calculating the average
float sum(account * temp) {
float average = 1.0, sum = 0.0;
int i;
account * start;
temp = start;
for (i = 0; i < t; i++) {
sum += temp -> total;
temp = temp -> nextptr;
}
average = sum / t;
return average;
}
int main() {
int selection;
account * start = NULL;
account * save, * temp;
account * ptr;
ptr = (account * ) malloc(sizeof(account) * 8);
do {
//Menu
printf("\n1.Adding account\n");
printf("2.Find the average of the added accounts' balances\n");
printf("3.Exit\n");
scanf("%d", & selection);
switch (selection) {
case 1: {
if (ptr == NULL)
ptr = (account * ) realloc(ptr, sizeof(account));
save = addaccount(ptr);
if (start == NULL) {
start = save;
start -> nextptr = NULL;
} else {
temp = start;
while (temp -> nextptr != NULL)
temp = temp -> nextptr;
temp -> nextptr = save;
save -> nextptr = NULL;
}
break;
}
case 2: {
float avg;
avg = sum(temp);
printf("%f", avg);
break;
}
case 3: {
temp = start;
while (temp != NULL) {
free(temp);
temp = temp -> nextptr;
}
break;
}
}
} while (selection != 4);
return 0;
}
Look here
// function for calculating the average
float sum(account* temp) {
float average = 1.0, sum = 0.0;
int i;
account* start; <<<==== a random value
temp = start; <<<=== over write the parameter of this function with a random value
for (i = 0; i < t; i++) {
sum += temp->total;
temp = temp->nextptr;
}
average = sum / t;
return average;
}
Not sure what you are trying to do here - but that is for sure wrong
There are quite a number of problems with your code:
you say you want a maximum of 8 accounts, but there is no such limit being imposed by the code.
in sum() (which is misnamed, BTW), you are not looping through the nodes correctly, because the temp = start; assignment is backwards. start is uninitialized, and then temp is used inside the loop, thus invoking undefined behavior. You don't actually need the start variable at all, since you can simply increment the account* temp parameter.
in main(), you are initially pointing ptr to an array of 8 accounts, but if the user enters 1 on your menu, and ptr is NULL (which it would not be unless that initial malloc() failed), then you are pointing ptr to a single account. If your goal is to allow the user to enter an arbitrary number of accounts, your list management is all wrong.
Worse, every time the user enters 1 on your menu, you are calling addaccount() on the 1st account in the array, and addaccount() simply populates the specified account with data. So, you are not actually creating a new account and adding it to the list, at all. You are just linking the 1st account back to itself, over and over.
if the user enters 2 on your menu, you are calling sum() on the last account created by 1. If no account has been created yet, your code will crash since temp is uninitialized at that point. You need to call the function on the first account instead, so it can iterate the whole list.
if the user enters 3 on your menu, the code tries to free() individual accounts, but you did not actually malloc() individual accounts to begin with. You are trying to store accounts in an array instead, so you would just need to free() the array instead.
Also, your loop is checking for selection != 4, but your menu doesn't have an option 4. You should be checking for selection != 3 instead.
With that said, try something more like this:
#include <stdio.h>
#include <stdlib.h>
//node structure
typedef struct node {
int no;
char name[20];
float total;
struct node * nextptr;
}
account;
//adding accounts function
account* addaccount() {
account *temp = malloc(sizeof(account));
if (temp == NULL) {
printf("Unable to create new account\n");
return NULL;
}
fflush(stdin);
printf("Enter the account name: \n");
gets(temp->name);
printf("Enter the account number: \n");
scanf("%d", &temp->no);
printf("Enter the account balance: \n");
scanf("%f", &temp->total);
temp->nextptr = NULL;
return temp;
}
// function for calculating the average
float average(account* start) {
if (start == NULL) return 0.0;
float sum = 0.0;
int t = 0;
do {
sum += start->total;
start = start->nextptr;
++t;
}
while (start != NULL);
return sum / t;
}
int main() {
int selection;
account *start = NULL, *last = NULL, *temp;
do {
//Menu
printf("1.Adding account\n");
printf("2.Find the average of the added accounts' balances\n");
printf("3.Exit\n");
scanf("%d", &selection);
switch (selection) {
case 1: {
if ((temp = addaccount()) == NULL) break;
if (start == NULL)
start = temp;
else
last->nextptr = temp;
last = temp;
break;
}
case 2: {
printf("%f\n", average(start));
break;
}
}
} while (selection != 3);
temp = start;
while (temp != NULL) {
free(temp);
temp = temp -> nextptr;
}
return 0;
}
I have created a function that is supposed to take the numbers in my linked list and determine which one is the smallest number and which one is the largest number. I created a while loop that is supposed to take each number and compare it to the next. 'newNumber' is the current number and 'next' should be the number next in the list. I am having trouble understanding how to call the current and next number. My while loop is also infinite is it because, I am referring to the numbers again in determine?
double NumberSize(NewNumber *start){
NewNumber *determine = start;
double SecondNumber =0;
double FirstNumber = 0;
while(determine != NULL){
FirstNumber = determine->newNum;
SecondNumber = determine->next;
if(FirstNumber < SecondNumber){
printf("The biggest number is:\n", SecondNumber);
}else{
printf("The smallest number is:\n", FirstNumber);
}
}
You forgot to step through the list. Using on of the solutions for the average:
void NumberSize(NewNumber * start)
{
double num = 0.0;
double biggest;
double smallest;
int flag = 0;
NewNumber *temp = start;
// set start values
if(tmp != NULL){
biggest = temp->newNum;
smallest = temp->newNum;
tmp = tmp->next;
flag = 1;
}
// while temp is not NULL
while (temp) {
// get number from current node
num = temp->newNum;
// if that number is bigger than "biggest"
if (num > biggest) {
// exchange "biggest" with "num"
biggest = num;
}
// do it the same way for the smallest number
else if (num < smallest) {
smallest = num;
}
// here is the forgotten line:
// go to the next node
temp = temp->next;
}
if(flag){
// no returns, just printing
printf("The smallest number is: \n", smallest);
printf("The biggest number is: \n", biggest);
} else {
puts("list empty");
}
}
I have a new problem. I got most of the things fixed. I need my (turnAgain) function fixed. I specifically need to fix my if else statement. I need it to let the player continue rolling if they type in 'r'. else if they type 'h' the other player gets to roll. And I need it to say try again type 'r' or 'h' if they type in something that is is not 'r' or 'h'. I just dont know how to do that. New to coding thanks!! I REALLY NEEEEEEEEEEEEEEEEEEEEEEED HELP.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>
#define SIDES 6
typedef enum {doublesPoints, onesPoints, noPoints, singlesPoints} status;
void prnRules(void)
// function: prnRules
// pre: none
// post: prints the rules
{
printf("%s\n",
"The goal is to be the first player to reach 50 points.\n\n"
"On a turn, a player rolls the two dice repeatedly until either a 1 is rolled \n"
"or the player chooses to hold and stop rolling.\n\n"
"If a 1 is rolled, that player's turn ends and no points are earned for the round.\n"
"If the player chooses to hold, all of the points rolled during that round are added to their score.\n\n"
"If a player rolls double 1s, that counts as 25 points.\n"
"Other doubles are worth 2x double points, so that a 2-2 is worth 8 points; 3-3 is worth 12; \n"
"4-4 is worth 16; 5-5 is worth 20; and 6-6 is worth 24.\n\n"
"When a player reaches a total of 50 or more points, the game ends and that player is the winner.\n");
}
int rollDie ()
// function: rollDie
// pre: none
// post: generates a random number for the die
{
int d;
d = rand() % SIDES + 1;
return d;
}
status turnPoints(int die1, int die2)
// function: turnStatus
// pre: dice have been rolled
// post: returns the status of the roll (doublesPoints, onesPoints, no Points, singlesPoints)
{
if (die1 == die2 && !(die1 == 1 && die2 == 1))
return doublesPoints;
else if (die1 == 1 && die2 == 1)
return onesPoints;
else if ((die1 == 1 || die2 == 1) && !(die1 == 1 && die2 == 1))
return noPoints;
else
return singlesPoints;
}
void turnAgain(int status)
{
char rollDie;
do
{
printf("Would you like to roll again or hold(r/h)?");
scanf("%c",&rollDie);
} while(rollDie!='r'&&rollDie!='h');
if(rollDie=='r')
{
}
else
{
}
//to switch the current player when the turn is over
int switchPlayer(int currentPlayer)
{
if (currentPlayer == 1)
return 2;
else
return 1;
}
char gameAgain()
// function: gameAgain
// pre: none
// post: returns a valid (y or n) answer
{
char ans;
do
{
printf("Play another game (y or n)? ");
ans = getchar();
getchar();
}while (ans != 'y' && ans != 'n');
return ans;
}
int gameOver (int p1Total, int p2Total)
// function: gameOver
// pre: none
// post: returns a '1' if either total exceeds 50
{
if (p1Total || p2Total >= 50)
{
return 1;
}
else
{
return 0;
}
}
//The final print statement with all the totals
void finalOutput(int p1Total, int p2Total)
// function: finalOutput
// pre: gameOver returns a '1'
// post: returns the final scores of the game
{
printf("\n");
printf("WE HAVE A WINNER!!!\n");
printf("Player 1 your final score was %d\n", p1Total);
printf("Player 2 your final score was %d\n", p2Total);
}
int updatePlayerTotal(int currentPlayer, int turnTotal, int playerTotal)
// function: pudatePlayerTotal
// pre: none
// post: returns the player total
{
printf("Player %d, your total at the start of this turn was %d .\n",
currentPlayer, playerTotal);
playerTotal = playerTotal + turnTotal;
printf("Your total at the end of this turn is %d.\n\n", playerTotal);
return playerTotal;
}
int main (void)
{//begin main
// variable declarations
int sum; // for sum of two dice
char answer; // for yes/no questions
int tempTotal = 0; // temporary player total for the round
int p1Total = 0; // running total for player 1
int p2Total = 0; // running total for player 2
int total = 0; // player total after each round
int die1 = 0; // the roll value of die1
int die2 = 0; // the roll value of die2
int currentPlayer = 1; // start with Player 1
int status = 0; // status for choice to continue
srand(time(NULL)); // seed random # generator
do // play at least one game
{//Begin game loop
//give option to view the rules
printf("Welcome to the game of Fifty. Would you like to view the rules? (y or n)?\n");
answer = getchar();
getchar();
if (answer == 'y')
prnRules();
do // until game is won
{//Begin roll loop1
{ //Begin roll loop2
die1 = rollDie();
die2 = rollDie();
sum = (die1 + die2);
printf("Player %d:\n", currentPlayer);
printf("Die 1 is a %d.\n", die1);
printf("Die 2 is a %d.\n", die2);
//award points (rolled a double but not double 1's)
if (turnPoints(die1, die2) == doublesPoints)
{
printf(" Player %d, you rolled a double %d!\n ", currentPlayer, die1);
printf(" That's worth %d points.\n", (sum * 2));
tempTotal = (tempTotal + total + (sum * 2));
status = 1;
}
//award points (rolled double 1's)
else if (turnPoints(die1, die2) == onesPoints)
{
printf(" Player %d, You rolled a double 1!\n ", currentPlayer);
printf(" That's worth 25 points.\n");
tempTotal = (tempTotal + total + 25);
status = 1;
}
//award no points (one of the two dice = 1)
else if (turnPoints(die1, die2) == noPoints)
{
printf("Sorry Player %d, you rolled a single 1. You do not earn any points this round\n", currentPlayer);
printf("Your current total is %d\n", total);
tempTotal = 0;
total = total + tempTotal;
status = 0;
}
//award points (rolled singles)
else if (turnPoints(die1, die2) == singlesPoints)
{
printf("Player %d, your roll totals %d points.\n", currentPlayer, sum);
tempTotal = tempTotal + (total + sum);
status = 1;
}
}while (status == 1 && (turnAgain(status) == 'y'));//end roll loop2 - while player continues roll
if (turnAgain(status) == 'n')//(answer == 'n')
{
total = (tempTotal + total);
if (currentPlayer == 1)
{
p1Total = updatePlayerTotal(currentPlayer, tempTotal, p1Total);
}
else
{
p2Total = updatePlayerTotal(currentPlayer, tempTotal, p2Total);
}
//switch players
currentPlayer = switchPlayer(currentPlayer);
}
}while (gameOver(p1Total, p2Total) != 1); //end loop1 - continue while game is not over
answer = gameAgain();
}while (answer != 'n'); //end game loop - loop while wanting to play again
return 0;
}//end main
int rollDie ()
// function: rollDie
// pre: none
// post: generates a random number for the die
{
int d;
d = rand() % SIDES + 1;
return d;
}
...
int turnAgain(int status)
---> you forget the left brace {
char rollDie; // Conflict, rollDie redeclared
Compile with warnings:
die1 = rollDie();
^
demo.c:60:10: note: declared here
char rollDie;
I have been trying to figure out why my code isn't working properly. I know my code below is a mess (I am a rather poor C programmer thus far). Its a work in progress. Specifically
printf("Please enter the index of the contact you wish to view. \nThis should be a positive integer\n\n");
scanf("%d", &vIndex);
fgetc(stdin);
printf("The value of vIndex is %d", &vIndex);
I find that when i run my program I might select a keyboard input of 1, meaning I am looking at my second record in my file entries.txt. The printout of vIndex however is a number much much larger, much likely the last information stored there. Running in debug however, i find that vIndex change to 1 and but prints the strange number. My entire code is below.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct rec
{
int i;
float PI;
char A;
} Record;
typedef struct
{
char fname[20];
char lname[50];
char phone[15];
} Contact;
Record * arrayAlloc(int size);
char * stringAlloc(int size);
Contact * contactAlloc();
void structAlloc();
int main(void)
{
int *ptrInt;
Record * ptrRec;
int i = 0;
char * myName;
Contact * contacts;
ptrInt = (int *)malloc(sizeof(int));
int vIndex=0;
int displayMenu();
Contact * contactAlloc();
// void searchIndex();
void searchFirst();
void searchLast();
void searchPhone();
contacts = contactAlloc();
char choice;
choice = displayMenu();
while (choice !=5)\
{
if (choice == 1)
// searchIndex();
{
printf("Please enter the index of the contact you wish to view. \nThis should be a positive integer\n\n");
// fgets(vIndex, 700, stdin);
scanf("%d", &vIndex);
fgetc(stdin);
printf("The value of vIndex is %d", &vIndex);
printf("You have selected to view the %d contact.\nFirst name:\t%c. \nLast Name:\t%c. \nPhone Number:\t%c.\n\n ", &vIndex, contacts[vIndex].fname, contacts[vIndex].lname, contacts[vIndex].phone);
}
else if (choice == 2)
searchFirst();
else if (choice == 3)
searchLast();
else if (choice == 4)
searchPhone();
choice = displayMenu();
}
printf("Thank for you using this program.\n");
return 0;
}
int displayMenu()
{
int choice = 0;
while (choice!= 1 && choice != 2 && choice != 3 && choice != 4 && choice!=5)
{
printf("\nWelcome to the phone book application. Please choose from the following options:");
printf("\n\n\t 1) Search the phone book by index. \n\t 2) Search the phone book by first name. \n\t 3) Search the phone book by last name. \n\t 4) Search the phone book by phone number. \n\t 5) Quit.\n\n");
scanf("%d", &choice);
}
return choice;
}
Contact * contactAlloc()
{
FILE * fin;
int count = 0, i = 0;
char aLine[100];
Contact * ptrContact;
fin = fopen("entries.txt", "r");
if (fin != NULL)
{
while( fgets(aLine, sizeof(aLine), fin) != NULL )
{
count++;
}
fseek(fin, 0L, SEEK_SET);
count = count / 3;
ptrContact = (Contact *) calloc(count, sizeof(Contact));
count = 0;
while( fgets(aLine, sizeof(aLine), fin) != NULL )
{
if (aLine[strlen(aLine) - 1] == '\n')
{
aLine[strlen(aLine) - 1] = '\0';
}
if (i % 3 == 0)
{
strcpy(ptrContact[count].lname, aLine);
}
else if (i % 3 == 1)
{
strcpy(ptrContact[count].fname, aLine);
}
else if (i % 3 == 2)
{
strcpy(ptrContact[count].phone, aLine);
//printf("Line %d at count %d: %s\n", i, count, aLine);
count++;
}
i++;
}
//count=count*3;
printf("%d contacts loaded.\n\n", count);
fclose(fin);
}
return ptrContact;
}
/*
void searchIndex()
{
int vIndex=0;
printf("Please enter the index of the contact you wish to view. This should be a positive integer");
scanf("%d", &vIndex);
fgetc(stdin);
printf("You have selected to view the %d contact.\nFirst name:\t%c. \nLast Name:\t%c. Phone Number:\t%c.\n\n ", &vIndex, &Contact[vIndex].fname, &Contact[vIndex].lname, &Contact[vIndex].phone);
}
*/
void searchFirst()
{
}
void searchLast()
{
}
void searchPhone()
{
}
You are printing the address of vIndex instead of the value:
printf("The value of vIndex is %d", &vIndex);
Change this line to the following:
printf("The value of vIndex is %d", vIndex);