本文介绍了使用fscanf()函数对与fgets()和sscanf()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这本书实用C语言程序设计,我觉得与fgets()的组合的sscanf()是用于读取输入。然而,在我看来,同样的目标可以更容易地只使用的fscanf()函数满足:

In the book Practical C Programming, I find that the combination of fgets() and sscanf() is used to read input. However, it appears to me that the same objective can be met more easily using just the fscanf() function:

这本书(的想法,而不是为例):

From the book (the idea, not the example):

int main()
{
    int age, weight;
    printf("Enter age and weight: ");

    char line[20];
    fgets(line, sizeof(line), stdin);
    sscanf(line, "%d %d", &age, &weight);

    printf("\nYou entered: %d %d\n", age, weight);
    return 0;
}

我怎么觉得应该是:

How I think it should be:

int main()
{
    int age, weight;
    printf("Enter age and weight: ");
    fscanf(stdin, "%d %d", &age, &weight);

    printf("\nYou entered: %d %d\n", age, weight);
    return 0;
}

或者有一些隐藏的怪癖,我失踪?

Or there is some hidden quirk I'm missing?

推荐答案

有两个方法的几个行为差异。如果你使用与fgets() + 的sscanf(),你必须在同一行中输入两个值,而的fscanf()标准输入(或等价, scanf()的)将阅读过不同的线路,如果它没有找到您所输入的第一行第二个值。

There are a few behavior differences in the two approaches. If you use fgets() + sscanf(), you must enter both values on the same line, whereas fscanf() on stdin (or equivalently, scanf()) will read them off different lines if it doesn't find the second value on the first line you entered.

不过,可能是最重要的差异与处理错误情况和线路输入导向和磁场定向输入的混合做。

But, probably the most important differences have to do with handling error cases and the mixing of line oriented input and field oriented input.

如果你读,你是无法与的sscanf()有使用读它之后与fgets()您的程序可以简单地放弃行,继续前进。然而,的fscanf(),当它不能转换领域,叶上的所有数据流的输入端。所以,如果你无法读取你想要的投入,你不得不去阅读所有你想忽略自己的数据。

If you read a line that you're unable to parse with sscanf() after having read it using fgets() your program can simply discard the line and move on. However, fscanf(), when it fails to convert fields, leaves all the input on the stream. So, if you failed to read the input you wanted, you'd have to go and read all the data you want to ignore yourself.

其他微妙的疑难杂症进来,如果你想混面向外地(ALA scanf()的)面向(如)线与fgets()调用您的code。当 scanf()的转换的 INT 例如,它会留下一个 \\ n 输入流(假设有一个,就像从pressing回车键),这将导致与fgets的后续调用()与输入仅字符立即返回。这是新程序员非常常见的问题。

The other subtle gotcha comes in if you want to mix field oriented (ala scanf()) with line oriented (e.g. fgets()) calls in your code. When scanf() converts an int for example, it will leave behind a \n on the input stream (assuming there was one, like from pressing the enter key), which will cause a subsequent call to fgets() to return immediately with only that character in the input. This is a really common issue for new programmers.

所以,虽然你是对的,你可以只用的fscanf()这样,您可以通过使用与fgets避免一些麻烦() + 的sscanf()

So, while you are right that you can just use fscanf() like that, you may be able to avoid some headaches by using fgets() + sscanf().

这篇关于使用fscanf()函数对与fgets()和sscanf()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 13:02