While 循环检索输入,在 C 中无法正常工作
我在使用允许验证输入的用户输入方法时遇到问题。 我需要在验证输入后返回输入。
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
导致未定义的行为!
fflush()
只能用于为输出而不是输入打开的流。Causes an Undefined Behavior!
fflush()
should only be used on streams open for output, not input.