这是我的代码,我正在使用代码块
#include <stdio.h>
struct engine {
char name[100];
int rpm;
int hp;
char manufacturer[100];
};
struct engine data;
int main()
{
printf("Please insert engine information \n");
printf("\nName: ");
fgets(data.name, 101, stdin);
printf("\nRPM:");
scanf("%d",&data.rpm );
printf("\nHorse Power:");
scanf("%d",&data.hp);
printf("\nManufacturer: ");
fgets(data.manufacturer, 101, stdin);
printf("\nParts information are as below\n");
printf("Name:%s\n",data.name);
printf("RPM:%d\n",data.rpm);
printf("Horse Power:%d\n",data.hp);
printf("Manufacturer:%s\n",data.manufacturer);
}
输入名称,rpm和hp的值后,程序停止。
我似乎无法找到问题所在
*编辑这是收到Alter Mann的帮助后的最终工作代码
#include <stdio.h>
struct engine {
char name[100];
int rpm;
int hp;
char manufacturer[100];
};
struct engine data;
static void flush_stdin(void)
{
int c;
while ((c = fgetc(stdin)) != '\n' && c != EOF);
}
int main()
{
printf("Please insert engine information \n");
printf("\nName: ");
fgets(data.name, sizeof(data.name), stdin);
printf("\nRPM:");
scanf("%d",&data.rpm );
printf("\nHorse Power:");
scanf("%d",&data.hp);
printf("\nManufacturer: ");
flush_stdin();
fgets(data.manufacturer, sizeof(data.manufacturer), stdin);
printf("\nParts information are as below\n");
printf("Name:%s",data.name);
printf("RPM:%d\n",data.rpm);
printf("Horse Power:%d\n",data.hp);
printf("Manufacturer:%s\n",data.manufacturer);
}
答案 0 :(得分:2)
您需要在fgets
:
static void flush_stdin(void)
{
int c;
while ((c = fgetc(stdin)) != '\n' && c != EOF);
}
int main(void)
{
printf("Please insert engine information \n");
printf("\nName: ");
fgets(data.name, sizeof(data.name), stdin); // don't use magic numbers like 101
printf("\nRPM:");
scanf("%d",&data.rpm );
printf("\nHorse Power:");
scanf("%d",&data.hp);
flush_stdin();
printf("\nManufacturer: ");
fgets(data.manufacturer, sizeof(data.manufacturer), stdin);
...
答案 1 :(得分:1)
fgets将收到'\ n'作为角色。
正如@Alter Mann建议的那样,你可以使用
scanf("%d%*c",&data.hp);
丢弃以下'\ n'。
或者,如果字符不包含空格,则可以使用scanf接收字符,例如
scanf("%s",&data.manufacturer);