[英]How to get rid of a white space line in C?
我是初学者,只是在 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
将显示 model 名称,一行空白,然后是相机和 ZCD69B4957F06CD818D7BF3D61980 连续行我想摆脱那一行空白。 我试图在所有%d
之前在scanf
中留下一个空格以丢弃该行,但它不起作用(我读过scanf
在您首先输入内容时读取换行符,为了防止这种情况,我们只需要添加一个空间以首先刷新缓冲区)。
在这里,您从控制台输入一行:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.