This is my code, Im using codeblock

#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);

}

The pogram stopped after input the values for name, rpm and hp.

I can't seem to find whats the problem

*Edit This is the final working code after receiving help from 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);

}
有帮助吗?

解决方案

You need to consume (flush) newline before 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);
    ...

其他提示

fgets will receive '\n' as a character.

as @Alter Mann suggests,you can use

scanf("%d%*c",&data.hp);

to discard the following '\n'.

Or you can use scanf to receive your characters if it doesn't contain blank space,like

scanf("%s",&data.manufacturer);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top