While 循环检索输入,在 C 中无法正常工作

发布于 2024-12-29 03:37:24 字数 1016 浏览 2 评论 0原文

我在使用允许验证输入的用户输入方法时遇到问题。 我需要在验证输入后返回输入。

char* getvalidinputnumber(int length, char prompt[],int base)
    {
        char* user_input = calloc(length+1,sizeof(char));

        fflush(stdin);
        fflush(FILE *);

        /*Prompts & Gets the users input and saves it in user_input*/
        do {
            printf("\n %s", prompt); 
            fgets(user_input,length+1,stdin); 
            /*printf("\n##Entered %s : ", user_input);*/
        } while(!isnumeric(user_input,base) && strlen(user_input) != length);

        fflush(stdin); 
        return(user_input);
    }

当在我的 main 中调用此函数时,例如......

while (strcmp(user_input,"00000000") != 0)
{
    user_input = getvalidinputnumber(8, "Enter HEX Value",16);
}

它还执行以下操作......

输入十六进制值

输入十六进制值

两次而不是一次,当我输入十六进制值时,它会返回正确的十六进制值,但然后再次运行两次我尝试使用 fflush 但这似乎无法解决问题。

我该如何解决这个问题,或者是否有更好的方法来获取输入,例如使用 scanf?

I have a problem when using a user input method which allow validates the input.
I require to return the input after its been validated.

char* getvalidinputnumber(int length, char prompt[],int base)
    {
        char* user_input = calloc(length+1,sizeof(char));

        fflush(stdin);
        fflush(FILE *);

        /*Prompts & Gets the users input and saves it in user_input*/
        do {
            printf("\n %s", prompt); 
            fgets(user_input,length+1,stdin); 
            /*printf("\n##Entered %s : ", user_input);*/
        } while(!isnumeric(user_input,base) && strlen(user_input) != length);

        fflush(stdin); 
        return(user_input);
    }

When calling this function within my main like....

while (strcmp(user_input,"00000000") != 0)
{
    user_input = getvalidinputnumber(8, "Enter HEX Value",16);
}

It also does the following ...

Enter HEX Value

Enter HEX Value

Twice rather than just once and when i enter a hex value it returns the hex correct but then runs twice again ive tryed using fflush but this doesnt seem to solve it.

How could i solve this or is there a better way to get the input for example using scanf?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不及他 2025-01-05 03:37:24
fflush(stdin)

导致未定义的行为! fflush() 只能用于为输出而不是输入打开的流。

fflush(stdin)

Causes an Undefined Behavior! fflush() should only be used on streams open for output, not input.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文