使用 scanf 检查输入参数 [英] using scanf to check input parameters

查看:63
本文介绍了使用 scanf 检查输入参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用 scanf 来检查我有正确数量的输入(在本例中为 2),并且代码工作正常,但是如果我输入 1 个输入,它只会等待一秒钟,如果我输入 3它只是丢弃第三个,我所做的任何事情都不会返回错误消息.已经搜索了一个答案,但没有找到我可以使用的任何东西,我问的原因是我用于该主题的教科书的代码与我在这里的代码完全相同(我复制了一个不同的 int_swap 示例词,它似乎也不起作用?有什么想法吗?对不起,如果这是一个愚蠢或简单的问题.

Trying to use scanf to check i have the right amount of inputs ( in this case 2), and the code works fine, but if i put in 1 input it just keeps waiting for a second, and if i put in 3 it just discards the 3rd, nothing i do will ever return the error message. Have searched for an answer, but not found anything i could use, the reason i ask is the text book i am using for this subject has the code exactly the same as i have it here ( i copied out a different example for int_swap word for word, and it doesn't seem to work either? Any ideas? Sorry if this is a stupid or easy question.

#include <stdlib.h>
#include <stdio.h>



void int_sort2(int*, int*);


int
main(int argc, char* argv[])
{
        int x, y;
        printf("Please enter 2 numbers : ");
        if(scanf("%d%d", &x, &y) != 2)
    { 
            printf("Error in numbers entered\n");
        exit(EXIT_FAILURE);
    }
printf("The original order was %d,   %d\n", x, y);
int_sort2(&x, &y);
printf("The sorted order is : %d,    %d\n", x,y);


return 0;
}


void
int_sort2(int *x, int *y)
{
if(*y < *x)
    {
        int temp;
        temp = *x;
        *x = *y;
        *y = temp;

    }

    return;
}

推荐答案

正如scanf的文档所说

成功时,函数返回成功填充的参数列表的项数.

它将返回加载的项目数,而不是您刚刚输入的项目数.

It will return the number of items that was loaded not the number of item that you just inputted.

解决方案:

在扫描之前计算整数的数量.

count the number of ints before you scanf it.

这篇关于使用 scanf 检查输入参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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