gpt4 book ai didi

c - 跳过 for 循环的一次迭代

转载 作者:行者123 更新时间:2023-11-30 14:45:20 28 4
gpt4 key购买 nike

附有代码和输出。

基本上它是第二次跳过我的输入。就像我启动代码一样,它让我输入一个选项,然后第二次跳过输入,直接转到开关的默认情况。

然后第三次它就会允许我输入。不明白为什么。

任何帮助将不胜感激。

哦,这是一个作业,所以我必须将输入放在 menu() 原型(prototype)中,并且必须使用开关在 main 中进行评估。

#include <stdio.h>
#include <unistd.h>

char menu(void);

int main(void){
int a;
char op;
for (a = 1; a != 0;) {
op = menu();
switch (op) {
case 'a':
printf("youre in a\n\n");
break;
case 'e':
printf("youre in e\n\n");
break;
case 'p':
printf("youre in p\n\n");
break;
case 's':
printf("youre is s\n\n");
break;
case 'm':
printf("youre in m\n\n");
break;
case 'x':
printf("youre in x\n\n");
a = 0;
break;
default:
printf("Invalid entry. Please choose valid option.\n\n");
break;
}//end switch
}//end while
return 0;
}//end main

//menu prototype
char menu(void){
char option;
printf("-------------------------------");
printf("\nWelcome To Virtual Art Gallery");
printf("\n-------------------------------");
printf("\nMenu - Select on of the following options:");
printf("\npress 'a': To add a painting");
printf("\npress 'e': To erase a painting");
printf("\npress 'p': To print data for all paintings");
printf("\npress 's': To print data for special paintings");
printf("\npress 'm': To modify data for a painting");
printf("\npress 'x': To exit the program");
printf("\noption: ? ");
option = getchar();
return option;
}//end menu()

Here's the output that I am getting

最佳答案

如果您在 main 中调用 op = menu() 之后添加以下行:

    printf("op = \'%c\'\n", op);

您会注意到,对于大多数输入来说,op 实际上是一个换行符。这是因为 getchar 正在消耗 stdin 中的潜在换行符,而不是您实际输入的字符。

一些解决方法:

  1. 在循环中使用 getchar,首先删除所有换行符:

    do
    {
    option = getchar();
    }
    while(isspace(option));
  2. 使用 scanf 并在 "%c" 格式说明符之前添加一个空格:

    scanf(" %c", &option);

    scanf 格式字符串前的一个空格将自动消耗 stdin 中的任何潜在换行符。

关于c - 跳过 for 循环的一次迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53122405/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com