结构和fflush(stdin)

时间:2015-11-09 14:21:24

标签: c

#include <stdio.h>
#include <stdlib.h>

struct Person{
    char codeChacter[20];
    char fullName[30];
    int Iq, Eq;
};

int main(){
    struct Person cha1, cha2;

    printf("Enter detail of character 1: \n");
    printf("code Character: ");
    gets(cha1.codeChacter);
    fflush(stdin);
    printf("Full Name: ");
    gets(cha1.fullName);
    fflush(stdin);
    printf("Enter Iq and Eq: ");
    scanf("%d%d", &cha1.Iq, &cha1.Eq);

    printf("Enter detail of character 2: \n");
    printf("code Character: ");
    gets(cha2.codeChacter);
    fflush(stdin);
    printf("Full Name: ");
    gets(cha2.fullName);
    fflush(stdin);
    printf("Enter Iq and Eq: ");
    scanf("%d%d", &cha2.Iq, &cha2.Eq);

    printf("\n---------------------Detail------------------\n");
    printf("%s\t%s\t%d\t%d\n", cha1.codeChacter, cha1.fullName, cha1.Iq, cha1.Eq);
    printf("%s\t%s\t%d\t%d\n", cha2.codeChacter, cha2.fullName, cha2.Iq, cha2.Eq);
    return 0;
}

这是我的第一个结构计划。当我运行这个应用程序时,它工作,但它不适合我的想法。你能帮助我改变失败吗?非常感谢!

1 个答案:

答案 0 :(得分:0)

scanf("%d%d", (pointers to read));无法从输入流中删除换行符,然后gets会读取换行符并且无法正常工作&#34;期望&#34;

  • 请勿使用fflush(stdin);,这是未定义的行为。
  • 请勿使用存在缓冲区溢出风险的gets()

可能的解决方法:

#include <stdio.h>
#include <stdlib.h>

struct Person{
    char codeChacter[20];
    char fullName[30];
    int Iq, Eq;
};

char* read_line(char *out, size_t bufsize){
    char *lf;
    if (fgets(out, bufsize, stdin) == NULL) return NULL;
    /* remove the newline character because fgets store it while gets donesn't */
    for (lf = out; *lf != '\0'; lf++){
        if (*lf == '\n'){
            *lf = '\0';
            break;
        }
    }
    return out;
}

int main(void){
    char read_buf[1024];
    struct Person cha1, cha2;

    printf("Enter detail of character 1: \n");
    printf("code Character: ");
    read_line(cha1.codeChacter, sizeof(cha1.codeChacter));
    printf("Full Name: ");
    read_line(cha1.fullName, sizeof(cha1.fullName));
    printf("Enter Iq and Eq: ");
    read_line(read_buf, sizeof(read_buf));
    sscanf(read_buf, "%d%d", &cha1.Iq, &cha1.Eq);

    printf("Enter detail of character 2: \n");
    printf("code Character: ");
    read_line(cha2.codeChacter, sizeof(cha2.codeChacter));
    printf("Full Name: ");
    read_line(cha2.fullName, sizeof(cha2.fullName));
    printf("Enter Iq and Eq: ");
    read_line(read_buf, sizeof(read_buf));
    sscanf(read_buf, "%d%d", &cha2.Iq, &cha2.Eq);

    printf("\n---------------------Detail------------------\n");
    printf("%s\t%s\t%d\t%d\n", cha1.codeChacter, cha1.fullName, cha1.Iq, cha1.Eq);
    printf("%s\t%s\t%d\t%d\n", cha2.codeChacter, cha2.fullName, cha2.Iq, cha2.Eq);
    return 0;
}

使用此代码,您必须在同一行输入Iq和Eq,并且在输入Iq和Eq之前不能插入任何空白行,而使用scanf的程序不会要求这一点。