使用fgets刷新标准输入 [英] Flush stdin using fgets
问题描述
尝试通过控制台创建注册页面.我需要几个输入,并且我正在使用fgets,所以我需要刷新stdin.有关堆栈溢出的许多类似问题,都重定向到此处: http://c-faq.com/stdio/stdinflush2.html .我使用该链接获得了下面的代码.但是,这实际上不起作用.它说用户名:",然后当我输入用户名并按Enter时,它只是转到控制台中的新的空行,我可以在其中输入更多内容.为什么会这样呢?我该如何解决?
Trying to make a registration page through the console. I need several inputs for it, and I'm using fgets, so I need to flush stdin. Lots of similar questions on Stack Overflow redirected here: http://c-faq.com/stdio/stdinflush2.html. I got the code below using that link. However, this doesn't actually work. It says Username:, and then when I type in a username, and press enter, it just goes to a new, empty line in console where I can type in more. Why is this happening? How can I fix it?
添加了代码
NSLog(@"Do you have an account already?(1 for Yes, 0 for no)");
fgets(cnumb1, 2, stdin);
int c;
while((c = getchar()) != '\n' && c != EOF);
size_t length = strlen(cnumb1);
if (cnumb1 [length-1] == '\n'){ // In case that the input string has 1 character plus '\n'
cnumb1 [length-1] = '\0';} // Plus '\0', the '\n' isn't added and the if condition is false.
NSString* string = [NSString stringWithUTF8String: cnumb1];
if (string == 0) {
while(numb4 == 1) {
numb3 = 1;
while( numb3 == 1){
NSLog(@"Username:");
fgets(usercheck1, 13, stdin);
int c2;
while((c2 = getchar()) != '\n' && c2 != EOF);
size_t length1 = strlen(usercheck1);
if (usercheck1 [length1-1] == '\n'){ // In case that the input string has 12 characters plus '\n'
usercheck1 [length1-1] = '\0';} // Plus '\0', the '\n' isn't added and the if condition is false.
推荐答案
完全改写了我的答案,似乎我对问题的理解不够.
在用户再次按下回车键之前,应该清空输入缓冲区的行将不会得到任何结果-除非用户输入的字符超过了输入缓冲区可以容纳的字符数.
The line that is supposed to empty the input buffer will not get anything until the user presses return again - unless the user enters more characters than the input buffer can hold.
您应该首先检查 fgets
读取的字符串的长度,以及最后一个字符(在 \ 0
之前)是否是 \ n
,请勿尝试阅读更多字符.否则,像您一样清空输入缓冲区.
You should first check the length of string read by fgets
and if the last character (before the \0
) is a \n
, don't try to read more characters. Otherwise empty the input buffer like you did.
这篇关于使用fgets刷新标准输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!