如何摆脱C中的空白行?

问题描述 投票:1回答:1

我是一个初学者,只是学习C语言的结构,但是遇到了一个小问题。这是代码:

struct Phone{
    char name[50];
    double screensize;
    int memory;
    int camera;
};

int main(){

    struct Phone phone1;
    printf("What model do you have? ");
    fgets(phone1.name,50, stdin);
    printf("How many MP does the camera have? ");
    scanf(" %d", &phone1.camera);
    printf("How much memory does you phone have? ");
    scanf(" %d", &phone1.memory);

    printf("You entered you have: \n");
    printf("Model: %s \nCamera: %d \nMemory: %d", phone1.name, phone1.camera, phone1.memory);
}

它没有任何错误,但是当我运行它并输入我的东西时,代码中的最后一个printf将显示模型名称,一行空白,然后在连续的行中显示相机和内存。我想摆脱那行空白。我试图在所有scanf之前的%d中保留一个空格,以便丢弃该行,但是它不起作用(我读过scanf在您首先输入内容时会读取换行符,以防止那,我们只需要添加一个空间来首先刷新缓冲区)。

c scanf whitespace
1个回答
0
投票

您从控制台输入一行:

printf("What model do you have? ");
fgets(phone1.name,50, stdin);

它也捕获了'\n'字符,然后打印:

printf("Model: %s \nCamera: %d \nMemory: %d", phone1.name, phone1.camera, phone1.memory);
//             ^  ^ there you print that '\n' in phone1.name and second hardcoded
© www.soinside.com 2019 - 2024. All rights reserved.