DanMark
DanMark

Reputation: 75

Help with Prompting for and Storing Information

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

Upvotes: 3

Views: 86

Answers (2)

ak2
ak2

Reputation: 6778

Windows doesn't support line buffeting. By default, streams are unbuffered in the console window and on serial lines, and fully buffered elsewhere. As an alternative to flushing manually, buffering can be disabled with setvbuf().

Upvotes: 0

pmg
pmg

Reputation: 108938

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' or fflush(stdout).

Example
EDITED: the previous example used puts which already ends the output with a '\n'

int set_phone_number(struct contacts* c) {
    printf("\nWhat is your phone number?\n"); /* \n at end of output */
    scanf(" %d", &c->phone_number);
    return 0;
}

or

int set_phone_number(struct contacts* c) {
    printf("\nWhat is your phone number? ");
    fflush(stdout);                           /* force output */
    scanf(" %d", &c->phone_number);
    return 0;
}

Upvotes: 7

Related Questions