I have a block of code that takes input from stdin and stores it in a variable in a structure. then i go to print the contents of the structure but for some reason it keeps printing the last this entered from stdin.
after the user inputs their name and age, it goes back to the main menu where i choose to print names, option 3, which should print the name and age but it always prints 3 the last thing entered via stdin as opposed to the age previously entered
anyone know what the problem could be?
Thanks, ALain
ps. the program is nowhere neer complete for the task it needs to accomplish...ie. records placed in a sorted linked list..... so i appologize if bits and pieces confuse you the functions are not complete i just want to understand why i'm having this issue with stdin.
i'm compiling using gcc -ansi -Wall in a linux terminal.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <ctype.h>
#define MAX_LEN 250
struct node
{
char *name;
int age;
struct node *nextName;
struct node *nextAge;
};
typedef struct node NODE;
int drain_stdin()
{
int c;
while((c = getchar()) != '\n' && c != EOF );
return c;
}
void addStruct(NODE *info)
{
if (drain_stdin() != EOF )
{
printf("Enter name: ");
fgets(info->name, MAX_LEN + 1, stdin);
printf("Enter age: ");
scanf("%d", &info->age);
}
else
{
printf("An Error Has Occured\n");
}
}
void removeStruct(NODE *info)
{
if (drain_stdin() != EOF )
{
printf("Enter Name Of Desired Record To Be Removed");
fgets(info->name, MAX_LEN + 1, stdin);
}
else
{
printf("An Error Has Occured\n");
}
}
void printName(NODE *info)
{
printf("%s %d\n", info->name, info->age);
}
void printAge(NODE *info)
{
printf("%s %d\n", info->name, info->age);
}
/*
void exit(NODE *info)
{
free(info->name)
free(info);
}
*/
int main()
{
int choice;
NODE *info;
info = malloc(sizeof(NODE));
info->name = malloc(sizeof(char)*MAX_LEN);
do
{
printf("1. Add structure\n");
printf("2. Remove structure\n");
printf("3. Print names\n");
printf("4. Print ages\n");
printf("5. Exit\n");
scanf("%d", &choice);
if(choice == 1)
{
addStruct(&info);
}
else if(choice == 2)
{
removeStruct(&info);
}
else if(choice == 3)
{
printName(&info);
}
else if(choice == 4)
{
printAge(&info);
}/*
else if(choice == 5)
{
exit(&info);
}*/
else
{
return 0;
}
}while(choice != 5);
return 0;
}