The code below is supposed to prompt the user, step-by-step, for information. Currently, however, it waits for information and then display the prompts as well as the provided content. Can anyone explain why this is happening? Thanks.
contacts.h file
struct contacts {
int phone_number;
char first_name[11], last_name[11];
};
rolodex.c file
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "contacts.h"
int main(int argc, char* argv[]) {
struct contacts* c = (struct contacts*) malloc(sizeof(struct contacts));
if (c == 0) {
return 1;
}
set_first_name(c);
set_last_name(c);
set_phone_number(c);
display_contact(c);
}
int set_first_name(struct contacts* c) {
puts("\nWhat is your first name? ");
gets(c->first_name);
return 0;
}
int set_last_name(struct contacts* c) {
puts("\nWhat is your last name? ");
gets(c->last_name);
return 0;
}
int set_phone_number(struct contacts* c) {
printf("\nWhat is your phone number? ");
scanf(" %d", &c->phone_number);
return 0;
}
int display_contact(struct contacts* c) {
printf("\nName: %s %s Number: %d", c->first_name, c->last_name, c->phone_number);
return 0;
}
The standard output stream is line buffered by default. That means that output shorter than a whole line is not guaranteed to be seen before execution continues with other statements.
Either end your output with a
'\n'orfflush(stdout).Example
EDITED: the previous example used
putswhich already ends the output with a'\n'or