0

试图通过控制台制作一个注册页面。我需要几个输入,而且我正在使用 fgets,所以我需要刷新标准输入。很多关于 Stack Overflow 的类似问题都被重定向到这里:http ://c-faq.com/stdio/stdinflush2.html 。我使用该链接获得了以下代码。但是,这实际上不起作用。它显示用户名:,然后当我输入用户名并按 Enter 时,它只是转到控制台中的一个新的空行,我可以在其中输入更多内容。为什么会这样?我该如何解决?

编辑:添加代码

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.
4

1 回答 1

0

完全重写了我的答案,看起来我对问题的理解不够好。

在用户再次按下 return 之前,应该清空输入缓冲区的行不会得到任何东西 - 除非用户输入的字符多于输入缓冲区可以容纳的字符。

您应该首先检查读取的字符串的长度,fgets如果最后一个字符(在 之前\0)是 a \n,请不要尝试读取更多字符。否则像你一样清空输入缓冲区。

于 2013-07-12T18:14:53.503 回答