从stdin中读取fget时,为什么忽略第一个字符串? [英] Why is the first string ignored when reading with fgets from stdin?

查看:105
本文介绍了从stdin中读取fget时,为什么忽略第一个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
Dev-C ++输入已跳过

我正在尝试使用fgets从stdin中读取字符串数组,但是我要读取的第一个字符串始终被忽略.是什么导致此问题?

I am trying to read an array of character strings from stdin using fgets, but the first string I want to read is always ignored. What is causing this issue?

#include <stdio.h>

int main()
{
    int i;
    struct material
    {
        char name[30];
        float price, kg;
    };
    unsigned m,nr;
    printf("Lorry capacity=");
    scanf("%u", &m);
    printf("Number of materials=");
    putchar('\n');
    scanf("%u", &nr);
    struct material list[nr];
    for (i=0; i<nr; i++)
    {
        printf("Name=");
        fgets(list[i].name, 30, stdin);
    }
    putchar('\n');
    for (i=0; i<nr; i++)
    {
        printf("%s ", list[i].name);
    }
    return 0;
}

推荐答案

scanf("%u", &nr);
struct material list[nr];
for (i=0; i<nr; i++)
{
    printf("Name=");
    fgets(list[i].name, 30, stdin);

scanf(%u",& nr); 将换行符保留在输入缓冲区中,因此 fgets 查找空行而无需进一步输入输入.

The scanf("%u", &nr); leaves the newline in the input buffer, so fgets finds an empty line without requiring further input to be entered.

出于这个原因(尤其是其中一个原因),混合使用(f)scanf fgets 通常是一个坏主意.

It is generally a bad idea to mix (f)scanf and fgets, for that reason (among others).

作为快速解决方案,请在第一个 fgets

As a quick fix, empty the input buffer before the first fgets,

int ch;
while((ch = getchar()) != EOF && ch != '\n');
if (ch == EOF) {
    // oops
}

更原则性的修复方法是,在使用 fgets 获得包括换行符的整行之前读取值,并使用 strtoul 解码数字> sscanf .

A more principled fix would be to read in the values before using fgets to get an entire line including the newline, and decode the numbers with strtoul or maybe sscanf.

这篇关于从stdin中读取fget时,为什么忽略第一个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆