为什么我不能再次使用scanf函数在同一个变量,当第一线索失败(Why can't I us

2019-10-21 03:45发布

请看下面的代码:

#include <stdio.h>

int main(int argc, char const *argv[])
{
    int n;
    int i = scanf("%d", &n);
    printf("%d\n", i);
    int j = scanf("%d", &n);
    printf("%d\n", j);
    return 0;
}

假设我输入一个字符串n在第一时间, scanf将返回0 ; 然而,为什么它不会让我输入一个值n第二次和j是自动的0 ? 我应该怎么做,使之让我输入一个值n再次,即使我打在第一时间一个错误的价值?

Answer 1:

你几乎肯定进入一个非数字的值,这将导致第一scanf失败,返回零,(这是最重要的一点) 离开流指针它的确切位置是之前scanf调用。

这意味着未来你怎么称呼它的时候,它只会尝试读取相同的数据。

零返回值是一个大破绽- scanf返回成功扫描的项目数,所以零意味着你没有给它一个数字。

如果你输入数字,它工作正常,按下面的代码:

#include <stdio.h>

int main(int argc, char const *argv[])
{
    int n;
    int i = scanf("%d", &n);
    printf(">> %d %d\n", i, n);
    int j = scanf("%d", &n);
    printf(">> %d %d\n", j, n);
    return 0;
}

当您运行,并输入4132 ,你看:

41
>> 1 41
32
>> 1 32

在其职业生涯的一些点每个C程序员碰到用户输入该语言的不足之处。 基于线路输入您最好的选择是简单地发现是否良好的功能,然后使用sscanf结果字符串上。

一,确保线的基本单元,并能处理缓冲区溢出,并确保多余的数据不会“破坏”未来输入。

这里有一个我提前准备。



Answer 2:

您输入的非数字的字符串不会被消耗scanf

相反,你可以使用fgetssscanf是这样的:

#include <stdio.h>

int main(void)
{
    int n;
    char str[100];
    fgets(str, sizeof(str), stdin);
    int i = sscanf(str, "%d", &n);
    printf("%d\n", i);
    fgets(str, sizeof(str), stdin);
    int j = sscanf(str, "%d", &n);
    printf("%d\n", j);
    return 0;
}


Answer 3:

您可以重新进入输入和读取它们之前忽略该行的其余部分。 您可以忽略使用行的其余部分:

scanf("%[^\n]*\n");


Answer 4:

如果你输入数字代码将正常工作。 但是,当你输入一个字符串,则必须再次使用它之前从输入流串。


例如:

#include <stdio.h>

int main(int argc, char const *argv[])
{
    int n;
    char c;
    int i = scanf("%d", &n);
    printf("%d\n", i);
    //Remove the previous string from the input stream
    while ( (c = getchar()) != '\n' && c != EOF );
    int j = scanf("%d", &n);
    printf("%d\n", j);
    return 0;
}

当输入是整数输出

100
1
200
1

输出当输入字符串

abcd
0
efghi
0

更多参考: 为什么大家都说不要使用scanf函数? 我应该用什么呢?



文章来源: Why can't I use scanf on the same variable again when the first trail fails
标签: c scanf