gpt4 book ai didi

c - 我应该使用哪个函数从键盘获取输入?

转载 作者:太空宇宙 更新时间:2023-11-04 02:53:46 35 4
gpt4 key购买 nike

我正在学习 C,现在我想从键盘获得输入(2 个数字范围 [0,99] 并比较它们)。我发现了很多获取输入的选项:

  • 扫描()
  • 获取字符()
  • fgets()
  • 获取()

我尝试了其中的一些:

扫描:

#include<stdio.h>

main()
{
int flag=0,num1, num2;

printf("Give a number between 0-999");

do{

if(flag == 1){
printf("Wrong Input. Plz give a number between 0-99 ");
}
printf("\nnumber 1: ");
scanf("%d", &num1);
flag=1;
}while(num1<0 || num1>1000);

printf("Give one more");
flag=0;

do{

if(flag == 1){
printf("Wrong Input. Plz give a number between 0-99 ");
}
printf("\nnumber 2: ");
scanf("%d", &num2);
flag=1;
}while(num2<0 || num2>1000);

if(num1>num2){
printf("the max number is : %d\n", num1);
}else
if (num1<num2){
printf("the max number is : %d\n", num2);
}else
printf("they are equals\n");

但是,如果我按的不是数字,它会无限打印:

number 2: Wrong Input. Plz give a number between 0-99
number 2: Wrong Input. Plz give a number between 0-99
number 2: Wrong Input. Plz give a number between 0-99
// and goes on..

然后我尝试使用getchar:

#include<stdio.h>

main()
{
int flag=0;
char input1,input2;

printf("Give a number between 0-999");

do{

if(flag == 1){
printf("Wrong Input. Plz give a number between 0-99 ");
}
printf("\nnumber 1: ");
input1 = getchar();
flag=1;
}while(input1<0 || input1>1000);

printf("Give one more");
flag=0;

do{

if(flag == 1){
printf("Wrong Input. Plz give a number between 0-99 ");
}
printf("\nnumber 2: ");
input1 = getchar();
flag=1;
}while(input2<0 || input2>1000);

if(input1>input2){
printf("the max number is : %c\n", input1);
}else
if (input1<input2){
printf("the max number is : %c\n", input2);
}else
printf("they are equals\n");


}

但是这段代码不起作用。有什么建议吗?

最佳答案

scanf返回成功扫描的值的数量,或返回 -1 错误。因此,如果 scanf 没有返回 1,则说明出现了问题,您应该采取相应措施。


getchar 的问题在于它会返回一个字符(或 EOF 出错)。因此,如果您输入数字,则只会返回第一个数字,并且作为字符而不是数字。第二次调用 getchar 将返回第一个输入的第二个数字,作为一个字符。


我建议输入函数看起来像这样:

int get_input(void)
{
/* Infinite loop */
for (;;)
{
printf("Please enter a value between 1 and 9999 (inclusive): ");
fflush(stdout);

char buffer[256];

/* Read input from the user */
if (fgets(buffer, sizeof(buffer), stdin) == NULL)
{
perror("Error getting input");
return -1;
}

int value;

/* Extract an integer value from the input */
if (sscanf(buffer, "%d", &value) != 1)
{
printf("Your input was not a valid value.\n");
continue; /* Try to get input again */
}

/* Check for a valid value */
if (value >= 1 && value <= 9999)
return value; /* Got a value that is allowed */

printf("Not a valid value.\n");
/* Since we're in a loop, will continue from the beginning by asking for a value */
}

return -1; /* Must return a value */
}

调用此函数获取一个值,如果返回-1则出错:

int value1;
if ((value1 = get_input()) == -1)
exit(1); /* Error reading value */

关于c - 我应该使用哪个函数从键盘获取输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19540338/

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