在C中的while循环程序中打印了不需要的多个菜单

时间:2018-02-09 22:37:55

标签: c

C初学者,我试图学习编写菜单程序。以下是我的代码

ListWithFilterComponent

当我运行程序时。输入字符后,菜单打印两次。为什么程序会这样做?

从以下选项中选择一个菜单:

//A test file to test functions

#include <stdio.h>
#include <stdlib.h>

int enterChangeChar();
void printMenu();
char C = ' ';

int main()
{
char inputVal;
while (1)
    {
    printMenu();
    scanf("%c", &inputVal);
    switch (inputVal)
            {
            case 'c': enterChangeChar(); break;
            case 'q': exit(0);
            }
    }
return 0;
}

int enterChangeChar()
{
    int input;
    printf("Would you like to Enter or Change the Character value?\n\n");
    printf("Enter 1 to Assign OR 2 to Change the value of C: \n");
    scanf("%d", &input);    //input a integer value
    if(input == 1)
            {
            printf("Enter a character: \n");
            scanf(" %c", &C);
            printf("You entered: %c", C);
            }
    else if (input == 2)
            {
            printf("Change Value option selected\n");
            }
    return 0;
    }

void printMenu()
{
    printf("Select a menu choice from the options below: \n\n");
    printf("     OPTIONS                            INPUT\n");
    printf("Enter/Change Character                  'c'\n");
    printf("Quit Program                            'q'\n\n");
    printf("Enter your CHOICE:\n");
}

编辑:刚刚添加了我之前错过的printMenu()函数代码。

编辑2:也许我的问题不够明确。问题不在 OPTIONS INPUT Enter/Change Character 'c' Quit Program 'q' Enter your CHOICE: c Would you like to Enter or Change the Character value? Enter 1 to Assign OR 2 to Change the value of C: 1 Enter a character: v You entered: v Select a menu choice from the options below: OPTIONS INPUT Enter/Change Character 'c' Quit Program 'q' Enter your CHOICE: Select a menu choice from the options below: OPTIONS INPUT Enter/Change Character 'c' Quit Program 'q' Enter your CHOICE: q getchar。问题是用户输入一个字符后菜单打印两次,即使它只在整个程序中调用一次。

编辑3:最终编辑:伙计我现在知道了。 \ n在输入缓冲区中,无论何时给出选择,它都被计为输入,因此菜单被多次打印。谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

有未使用的换行符&#39; \ n&#39;在输入流中需要耗尽。

scanf()经常会引起混淆,因为它会留下尾随的&#39; \ n&#39;在输入流中。在您的情况下,后续的getchar()将获取换行符。

    int main()
{

    while (1)
    {
        char inputVal;
        printMenu();
        do {
            inputVal = getchar();
        } while (inputVal == '\n');

        switch (inputVal)
        {
        case 'c': enterChangeChar(); break;
        case 'q': exit(0);
        }
    }
    return 0;
}