gpt4 book ai didi

c - 在 C 中验证输入

转载 作者:太空宇宙 更新时间:2023-11-04 05:57:31 26 4
gpt4 key购买 nike

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

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

无效的代码:

#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” block ,它就会起作用。

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

检查负值的第二个 if block 也不起作用。

最佳答案

问题中显示的代码中有两个问题(编辑前):

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

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

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

关于c - 在 C 中验证输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24556696/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com