在C中重复循环

时间:2012-03-28 23:49:56

标签: c input newline scanf

问题我输入y作为选项,它会在再次提示我之前打印两次文本,因为它应该只打印一次。

正确的输出(我应该得到但未得到的):

Do you order FISH (Y/N)? y
Fish choice (K- Haddock, T- Halibut)

Do you order FISH (Y/N)? y
Fish choice (K- Haddock, T- Halibut)

Do you order FISH (Y/N)? n

Do you order CHIPS (Y/N)? n

Do you order DRINKS (Y/N)? y
Drinks choice (S- Softdrink, C- Coffee, T- Tea)

Do you order DRINKS (Y/N)? n

错误输出(我得到的输出)

Do you order FISH (Y/N)? y
Fish choice (K- Haddock, T- Halibut)
Do you order FISH (Y/N)? Fish choice (K- Haddock, T- Halibut)
Do you order FISH (Y/N)? y
Fish choice (K- Haddock, T- Halibut)
Do you order FISH (Y/N)? Fish choice (K- Haddock, T- Halibut)
Do you order FISH (Y/N)? n
Do you order CHIPS (Y/N)? Chips choice (C- Cut, R- Ring)
Do you order CHIPS (Y/N)? n
Do you order DRINKS (Y/N)? Drinks choice (S- Softdrink, C- Coffee, T- Tea):
Do you order DRINKS (Y/N)? n

RAW SOURCE (如果您想自己编译并查看最新信息):http://pastebin.com/raw.php?i=mZ1jVrF0

来源

#include <stdio.h>
#include <string.h>

int main() {

    char fishYesNo, chipsYesNo, drinksYesNo;
    char *typeOfFood;

    do {
        typeOfFood = "fish";
        printf("Do you order FISH (Y/N)? ");
        scanf("%c", &fishYesNo);
        if (fishYesNo != 'n') {
            printf("Fish choice (K- Haddock, T- Halibut) \n");

        }
        else if (fishYesNo == 'n') {
            typeOfFood = "chips";
        }

    } while ((strcmp(typeOfFood, "fish")) == 0);

    do {
    typeOfFood = "chips";
        printf("Do you order CHIPS (Y/N)? ");
        scanf("%c", &chipsYesNo);
        if (chipsYesNo != 'n') {
            printf("Chips choice (C- Cut, R- Ring) \n");
        }
        else if (chipsYesNo == 'n') {
            typeOfFood = "drinks";
        }

    } while ((strcmp(typeOfFood, "chips")) == 0);

    do {
    typeOfFood = "drinks";
        printf("Do you order DRINKS (Y/N)? ");
        scanf("%c", &drinksYesNo);
        if (drinksYesNo != 'n') {
            printf("Drinks choice (S- Softdrink, C- Coffee, T- Tea):\n");
        }
        else if (drinksYesNo == 'n') {
            typeOfFood = "fish";
        }

    } while ((strcmp(typeOfFood, "drinks")) == 0);

}

1 个答案:

答案 0 :(得分:6)

这是C中一个众所周知的概念错误。comp.lang.c FAQ(我建议你阅读)有很多关于这个和其他陷阱的信息。

解释代码中发生了什么(comp.lang.c FAQ list · Question 12.18b):

  

您希望scanf %c读取单个字符,并且尝试了,但是   当你试图在它的其余部分之前输入那个单个字符时   输入系统会接受它,你也必须点击RETURN键。   scanf只读取一个字符,但额外的换行符仍然存在   坐在某处的输入缓冲区中,它就是额外的换行符   (似乎代表一个幻影空白行)被收到了   你以后的输入电话。

如何处理这一问题,请查看scanf的问题(comp.lang.c FAQ list · Question 12.20):

  

几乎不可能优雅地处理所有这些潜力   使用scanf时遇到的问题;它更容易阅读整行(有   fgets等等,然后使用sscanf或其他方式解释它们   其他技术。