为什么我不能在第一个路径失败时再次对同一个变量使用 scanf [英] Why can't I use scanf on the same variable again when the first trail fails

查看:50
本文介绍了为什么我不能在第一个路径失败时再次对同一个变量使用 scanf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请查看以下代码:

#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 的值,即使我第一次输入了错误的值?

Suppose I input a string for n at the first time, scanf will return 0; however, why it won't allow me to input a value for n the second time and j is automatic 0? What should I do to make it allow me to input a value for n again even if I typed a wrong value at the first time?

推荐答案

您几乎肯定会输入一个非数字值,这将导致第一个 scanf 失败,返回零和(这是重要的一点)将流指针留在 scanf 调用之前的位置.

You're almost certainly entering a non-numeric value, which will cause the first scanf to fail, returning zero and (this is the important bit) leaving the stream pointer exactly where it was before the scanf call.

这意味着下一次调用它时,它只会尝试读取相同的数据.

That means the next time you call it, it will simply try to read the same data.

零的返回值是一个死的赠品 - scanf 返回成功扫描的项目数,所以零意味着你没有给它一个数字.

The return value of zero is a dead giveaway - scanf returns the number of items successfully scanned, so zero means you didn't give it a number.

如果您输入数字,它可以正常工作,按照以下代码:

If you enter numbers, it works fine, as per the following code:

#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 时,你会看到:

When you run that and enter 41 and 32, you see:

41
>> 1 41
32
>> 1 32

每个 C 程序员在其职业生涯的某个阶段都会遇到该语言中用户输入的不足之处.基于行的输入的最佳选择是简单地找到一个可以很好地完成它的函数,然后在结果字符串上使用 sscanf.

Every C programmer at some point in their career comes up against the inadequacies of user input in that language. Your best bet for line based input is to simply find a function that does it well, then use sscanf on the resultant string.

确保行是基本单位的一种,可以处理缓冲区溢出并确保多余的数据不会破坏"未来的输入.

One that ensures lines are the basic unit, and can handle buffer overflows and making sure excess data doesn't "corrupt" future input.

这是一个我早点准备.

这篇关于为什么我不能在第一个路径失败时再次对同一个变量使用 scanf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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