gpt4 book ai didi

c - 在下面的代码中刷新标准输入缓冲区时不知道哪里出了问题

转载 作者:行者123 更新时间:2023-11-30 19:07:00 25 4
gpt4 key购买 nike

I have attached output image of my program. you can see the problem i am facing by clicking here

下面的代码是我的程序,用于读取用户输入的字符,并使用我自己版本的内置函数 isalpha() 和 isalnum() 的 my_isalpha() 和 my_isalnum() 函数检查它是字母还是数字。 )。不适用于 while 循环的第二次迭代

#include <stdio.h>
#define NUM 1
#define ALPHA 2
#define ASCII 3
#define BLANK 4


int main()
{
char option;

do
{
//declaration of function
char character;
int user_option, status;

//get the character from the user
printf("Enter the Character:");

//clears both buffers to read the character
fflush(stdin);
fflush(stdout);


//reads one character at a time
character = getchar();

//prompt the user for the option to check
printf("Choice Below Option\n");
printf("1.isalnum\n2.isalpha\n");
printf("Enter your Option:");
scanf("%d", &user_option);

//validation of the user_option
switch(user_option)
{
case 1:
status = my_isalnum(character);
if(status == NUM)
{
printf("Character '%c' is an number", character);
}
else
{
printf("Character '%c' is not a number", character);
}
break;

case 2:
status = my_isalpha(character);
if(status == ALPHA)
{
printf("Character '%c' is an Alphabet", character);
}
else
{
printf("Character '%c' is not Alphabet",character);
}
break;
default:
puts("Invalid Choice.....");
}

printf("\nDo you want to continue?[Y/N]:");
scanf(" %c", &option);
}while (option == 'Y' || option == 'y');
fflush(stdin);
fflush(stdout);
return 0;
}
//Function chaecks for the Number
int my_isalnum(char character)
{
return (character >= '0' && character <= '9')? NUM : -1;
}

//functionn checks for the alphabets
int my_isalpha(char character)
{
return (character >= 'a' && character <= 'z' || character >= 'A' && character <= 'Z') ? ALPHA: -1;

}

上面的代码第一次工作正常,但在 while 循环的第二次迭代期间。当我给出“Y”作为输入代码时,直接跳转到 scanf 的 user_option 部分,而不是等待“getchar()”函数。

即使使用 fflush() 函数刷新缓冲区后,我也无法提示程序输入字符。

最佳答案

刷新stdin是未定义的行为。刷新是针对输出流而不是输入流。

根据标准§7.21.5.2

If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.

另外int getchar(void):get char()返回一个int

快速修复:从代码中删除 fflush(stdin)

printf("\nDo you want to continue?[Y/N]:");
scanf(" %c", &option);
getchar(); // this dummy getchar() will consume the `\n` from stdin.
}while (option == 'Y')

注意:

另外,正如其他解决方案建议使用 fpurge() 一样,这是一个选项,但它又是非标准且不可移植的

关于c - 在下面的代码中刷新标准输入缓冲区时不知道哪里出了问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47245943/

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