帮助提示和存储信息

问题描述:

下面的代码是supposed提示用户一步一步的信息。然而,目前它等待信息,然后然后显示提示以及提供的内容。任何人都可以解释为什么会发生?谢谢。帮助提示和存储信息

contacts.h文件

struct contacts { 
    int phone_number; 
    char first_name[11], last_name[11]; 
}; 

rolodex.c文件

#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; 
} 
+2

不要使用'gets()'。这是不安全的,不可能使其安全。使用'fgets()'来替代:'fgets(c-> last_mame,sizeof c-> last_name,stdin);' – pmg 2011-04-07 22:34:10

+0

+1对于正确询问相关代码的问题。 – pmg 2011-04-07 22:41:06

标准输出流线默认缓冲。这意味着在执行继续执行其他语句之前,不能保证看到比整行更短的输出。

'\n'fflush(stdout)结束输出。


编辑:使用puts前面的例子中,其已结束与一个'\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; 
} 

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

感谢关于'gets'的提示以及标准输出流是行缓冲的解释。我尝试了上面提到的两种方法(用'\ n'终止一行并刷新输出),只有后一种方法有效。任何想法为什么? – DanMark 2011-04-07 22:48:35

+0

两者都应该工作。我不知道为什么'fflush(stdout)'工作并且用'\ n''终止'printf()'不会。什么是您的硬件,操作系统,编译器,编译选项?也许在你的系统中,'stdout'默认是完全缓冲的(我认为这是标准非法的)... – pmg 2011-04-07 22:55:14

+0

我在'gcc'的vista上使用'msys(mingw32)',编译cmd是:'gcc -o rolodex rolodex.c'。 – DanMark 2011-04-07 22:59:57

视窗的输出不支持线抖振。默认情况下,流在控制台窗口和串行线路上无缓冲,并在其他地方完全缓冲。作为手动刷新的替代方法,可以使用setvbuf()来禁用缓冲。