0

我有一个让我困惑的小程序。我正在尝试使用循环来获取用户的输入。如果输入错误,则再次重复,但如果输入正确,则退出。代码片段是:

void main()
{
    char user_status; // Checks User Status q = Quiz Master and p = Participant
    int valid_status = '0'; // Checks If User Status Is Valid Or Not. Used In Some Loops. 0 = Invalid, 1 = Invalid.
    printf("Welcome to General Knowledge Quiz Management System.\nThis application has been designed to help you conduct a quiz or test your GK.");
    do
    {
        user_status = '0';
        printf("\n\nPlease enter your role.\nQuiz Master = \'q\'\nParticipant = \'p\'\n");
        scanf("%c", &user_status);
        if (user_status == 'q'|| user_status == 'Q')
        {
            printf("Initializing Quiz Master Segment\n\n________________________________\n");
            initiate_qm();
            valid_status = '1';
        }
        else if (user_status == 'p' || user_status == 'P')
        {
            printf("Initializing Participant Segment");
            initiate_pa();
            valid_status = '1';
        }
    }
    while (valid_status != '1')
        printf("\nProgram Will Exit Now. Press Any Key To Return To Windows.");
    getch();
}

我期待这个输出:

Please Enter Your Role 
Quiz Master = 'q' 
Participant = 'p'

到目前为止,它工作得很好。当我输入 q/Q/p/P 时,效果很好。但是当我输入错误时,它不会提供所需的输出。

例如,如果我输入“abc”,我应该再次得到上面的文本,要求我输入 q 或 p。但相反,我得到了这个:

 Please Enter Your Role 
 Quiz Master = 'q' 
 Participant = 'p' 
 Please Enter Your Role 
 Quiz Master = 'q' 
 Participant = 'p'
 Please Enter Your Role 
 Quiz Master = 'q' 
 Participant = 'p'
 Please Enter Your Role 
 Quiz Master = 'q' 
 Participant = 'p'
 _ (I have to input here)

现在,为什么要重复3次。需要注意的一件有趣的事情是,如果我输入的内容是 2 个字符长,它会额外重复 2 次,如果我将其留空(只需按回车键),它就不会重复额外的次数。

我只能使用 C。我正在使用 Visual C++ 2010 进行编译。

谢谢。

4

3 回答 3

4

因为你给了 scanf 三个字符来处理。它在第一次调用 scanf 获取“a”时删除第一个第一个字符,但在 stdin 缓冲区中仍然有“bc”。

在再次查找输入之前,您需要检查缓冲区中的剩余内容。而且我会避免刷新标准输入缓冲区,因为它是未定义的行为。(http://www.gidnetwork.com/b-57.html)

您可以读取剩余的字符并将其丢弃

do{  
    scanf("%c", &user_status);  
}while(user_status!='\n'); //This discards all characters until you get to a newline

在你读到你想要的角色之后。

于 2011-03-07T06:01:51.353 回答
1

你要

do
{

} while (condition);

当您忘记分号时,您会得到:

do
{
    ....
}

while(condition)
    do something else;

您可能已经注意到,只需像我在您的问题上所做的那样在编辑器中自动缩进您的代码。

此外,当您执行某些操作时,scanf您应该将 包含\n在格式规范中。

于 2011-03-07T05:59:02.713 回答
0

首先,# include <stdio.h>getc(stdin)用来获取一个字符。它将帮助您防止光标移动并将不必要的字符放入控制台。其次,在循环之前写下欢迎信息。

于 2011-03-07T06:15:30.030 回答