I'm building an Address Book to store an individuals name, address and phone number. I'm having trouble with the append function.
struct node{
char name[21];
char address[101];
char phone[15];
struct node *next;
};
void append(){
if(root == NULL){ // Empty list
struct node *temp = (struct node*) malloc(sizeof(struct node));
printf("Enter Name: ");
fgets(temp->name,20,stdin);
printf("Enter Address: ");
fgets(temp->address,100,stdin);
printf("Enter Phone Number: ");
scanf("%s",&temp->phone);
}
}
For the name and address I except the user to enter a string with whitespaces so I decided to use fgets(). However, I'm not sure how to store the name or address the user enters into the node. When I run my program fgets() is not called for the name, instead it jumps to the address and then asks the user to enter a phone number.
fgets(); by specifying 20 instead of 21, you are potentially wasting the last byte oftemp->name, for example. Better, usesizeof(temp->name)instead of either 20 or 21. You still have to worry about what happens if some brute types 'Caractacus Sophocles MacWhorter' as their name. Maybe you should have a big buffer (char buffer[4096];for example) and useif (fgets(buffer, sizeof(buffer), stdin) == 0) { …handle EOF or error… }and then drop the newline (buffer[strcspn(buffer, "\n")] = '\0';and then decide whether the string is short enough to fit. - Jonathan Lefflerfgets()twice withscanf()once is a recipe for trouble. Thescanf()leaves the newline in the input — so the next time you call the function, the newline is read by the firstfgets(), so the next entry has an empty name. That isn't what you want. Usefgets()consistently. - Jonathan Lefflernew linecharacter in the input buffer might cause a problem. - Jithin Pavithranfflush(stdin)just before 1st input statement and see if the problem is solved. - Jithin Pavithran