验证 C 中的输入 [英] Validate input in C

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

问题描述

我想编写一个程序,以便读取两个正整数作为输入,如果用户输入的不是两个正整数,则拒绝.我尝试使用以下代码,但它不起作用.

I want to write a program so to read two POSITIVE INTEGER as input and reject if the user inputs anything other than two positive integers.I tried to use the following code but it does not work.

编辑 1:删除了第一个 scanf.编辑 2:添加了检查负值的代码.

EDIT 1: Removed the first scanf. EDIT 2: Added code to check for negative values.

不起作用的代码:

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

int main () {

unsigned int no1,no2,temp;
char check;
printf("Enter two positive integers.\n");
scanf("%i %i %c", &no1, &no2 ,&check);

if(scanf("%i %i %c", &no1, &no2,&check) != 3 || check != '\n'){
    printf("Invalid input!!.\n");
    exit(EXIT_FAILURE);

}
else if (no1 <= 0 || no2 <= 0) {

        printf("Invalid input!!.\n");
        exit(EXIT_FAILURE);

     }



int copy1,copy2;

copy1 = no1;
copy2 = no2;

while(no2 != 0) {

    temp = no1 % no2 ;
    no1 = no2;
    no2 = temp ;
}

printf("The H.C.F. of %i and %i is %i. \n",copy1,copy2,no1);

return 0;

}

工作代码:

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

int main () {

int no1,no2,temp;

printf("Enter two positive integers.\n");
int numArgs = scanf("%i%i", &no1, &no2 );


if( numArgs != 2|| no1 <= 0 || no2 <= 0 ){
    printf("Invalid input!!.\n");
    exit(EXIT_FAILURE);
}




int copy1,copy2;

copy1 = no1;
copy2 = no2;

while(no2 != 0) {

    temp = no1 % no2 ;
    no1 = no2;
    no2 = temp ;
}

printf("The H.C.F. of %i and %i is %i. \n",copy1,copy2,no1);

return 0;

}

它一直持续到我连续输入 5 个整数或 2 个字符而不是 \n.它从不计算 H.C.F.但是,如果我删除if"块,它会起作用.

It goes on till I input 5 integers or 2 characters consecutively other than \n. It never computes the H.C.F. However it works if I remove the "if" block.

编辑 3:现在我不想阅读换行符.

EDIT 3: Now i do not want to read the newline.

检查负值的第二个 if 块也不起作用.

The second if block to check for negative values is also not working.

推荐答案

你的代码有两个问题如问题所示(编辑前):

You have two problems in the code as shown in the question (before the edit):

  1. 您为相同的变量调用 scanf 两次,迫使用户输入相同的数据两次.

  1. You call scanf twice for the same variables, forcing the user to input the same data twice.

所使用的格式不会读取换行符,因此表达式 check != '\n' 将始终为真.

The format used will not read a newline, so the expression check != '\n' will always be true.

对于数字 1,只需删除第一个 scanf 调用.对于数字 2,用户必须按 Enter 键结束输入,因此无需检查.如果您真的想确定,请使用例如fgets 读取包含两个数字的行,并使用 sscanf 来解析值.

For number 1, just remove the first scanf call. For number 2, the user must press the Enter key anyway to end the input, so no need to check for that. If you really want to be sure, then use e.g. fgets to read a line with both number in it, and use sscanf to parse the values.

这篇关于验证 C 中的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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