【问题标题】:Cannot input data, Output seems weird in C [duplicate]无法输入数据,输出在 C 中似乎很奇怪 [重复]
【发布时间】:2014-04-20 17:56:12
【问题描述】:

这是我的代码,我正在使用代码块

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

}

输入name、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);

}

【问题讨论】:

  • 旁注:fgets() 的第二个参数应该是字符缓冲区的大小(而不是更多)。
  • @MartinR 给出的答案是在格式末尾使用“%*[^\n]%*c”,请您解释一下我应该把它放在哪里。是不是在scanf里面比如scanf("%d%*[^\n]%*c",&data.hp);
  • 对于您的最后一次编辑,nops,那是多余的,如果您在最后使用 flush_stdin 刷新,请不要更改您的 scanf
  • 谢谢,改回来了

标签: c codeblocks


【解决方案1】:

您需要在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);
    ...

【讨论】:

  • 感谢这对我帮助很大
【解决方案2】:

fgets 将接收 '\n' 作为字符。

正如@Alter Mann 建议的那样,您可以使用

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

丢弃后面的'\n'。

或者你可以使用 scanf 来接收你的字符,如果它不包含空格,比如

scanf("%s",&data.manufacturer);

【讨论】:

  • 你是对的,谢谢你的建议。
猜你喜欢
  • 2023-01-29
  • 1970-01-01
  • 2021-05-16
  • 2018-09-12
  • 2015-03-26
  • 1970-01-01
  • 2019-03-27
  • 2015-10-19
  • 1970-01-01
相关资源
最近更新 更多