在C语言中只打印一次

3
如何在几次错误输入后仅打印一次语句:
例如:
如果输入了 kkk,则仅会打印一次语句,而不是像下面的示例那样。
示例输出:
您是否要重试(输入 Y 继续,输入 Q 退出):kkk
错误:无效选择
您是否要重试(输入 Y 继续,输入 Q 退出):错误:无效选择
您是否要重试(输入 Y 继续,输入 Q 退出):错误:无效选择
您是否要重试(输入 Y 继续,输入 Q 退出):
valid=0;
while (valid==0)
{
    printf("\nDo you wish to try again (Type Y to continue Q to quit:"); 
    // print statement request for input
    scanf(" %c", &choice); // get user input
    choice = toupper(choice);
    if((choice == 'Y') || (choice == 'Q')) 
        valid= 1;
    else 
        printf("Error: Invalid choice\n"); // statement
}
3个回答

4

你的scanf当前正在寻找单个字符(%c),所以当你输入 "kkk" 并按下回车键时,它会接收到四次输入:'k'、'k'、'k' 和 '\n'

改为使用%s,然后只检查你获得的字符串的第一个字符。

或者如评论中所说,使用fgets获取一个字符串,并按照上述方法处理它。


1
由于scanf格式说明符"%c",您的代码每次只检查1个字符。这意味着您的scanf在第一次输入回车键后就退出了,然后,在下一次调用中,对于用户输入的所有字符立即返回。
为避免出现这种行为,您可以一次性获取整个输入。
您可以尝试以下操作:
#include <stdio.h>
#include <ctype.h>

int main (void)
{
    int valid=0;
    char choice[32];
    size_t i=0;
    int data;

    while (valid==0)
    {
        printf("\nDo you wish to try again (Type Y to continue Q to quit):"); // print statement request for input

        fgets(choice, sizeof(choice), stdin);

        i=0;

        while ((choice[i] != '\0') && (valid == 0))
        {
            data = toupper((unsigned char)(choice[i]));

            if((data == 'Y') || (data == 'Q'))
            {
                valid= 1;
            }

            i++;
        }

        if (valid == 0)
            printf("Error: Invalid choice\n"); // statement
    }
}

您可以看到,我使用了fgets从用户那里获取输入并将其存储在缓冲区中,以一次性存储整个输入(多个字符)。

之后,您可以循环遍历输入字符,并检查其中一个字符是否是正确的选择。


2
如果choice[i]具有负值而不是EOF,则toupper(choice[i]);是未定义行为。可以使用toupper((unsigned char) choice[i]);来确保这种情况不会发生。 - chux - Reinstate Monica

1
如何在多次错误输入时只打印一次语句
  • One way of doing it is to scan the input into string and compare the first element against 'Y' and 'Q' as other answers have shown you how to do.

  • However, If you don't want to use strings then, second way without using strings is to consume the additional characters after scanning the input using a loop this way:

    int valid=0;
    char choice;
    
    while (valid==0)
    {
        printf("\nDo you wish to try again (Type Y to continue Q to quit:"); 
    
        scanf("%c", &choice); 
        // remove space before format specifier as you are consuming white spaces in the below loop
    
    
        //consuming additional characters mechanism:
    
        int consume_char; //to store consumed character (getchar() returns int)
    
        //the below loop consumes all additional characters
        while( ( (consume_char = getchar()) != '\n' ) && (consume_char != EOF)); 
    
    
        choice = (char) toupper(choice);
    
        if((choice == 'Y') || (choice == 'Q')) valid= 1;
        else printf("Error: Invalid choice\n"); // statement
    }
    return 0;
    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接