|
发表于 2018-10-7 16:31:50
|
显示全部楼层
- #include<stdio.h>
- int main() // 请输入星期几的第一个字母来判断一下是星期几,如果第一个字母一样,则继续判断第二个字母。
- {
- char ch;
- printf("please input the first letter of someday!\n");
- while ((ch = getchar()) != 'y')
- {
- fflush(stdin);
- switch (ch)
- {
- case 'm':
- printf("monday\n");
- printf("please input the first letter of someday!\n");break;
- case 'f':
- printf("friday\n");
- printf("please input the first letter of someday!\n");break;
- case 'w':
- printf("wednesday\n");
- printf("please input the first letter of someday!\n");break;
- case 't':
- printf("please input the second letter of someday!\n");
- if ( (ch = getchar()) == 'u')
- printf("tuesday\n");
- else if (ch == 'h')
- printf("thursday\n");
- else
- printf("input error!!!\n");
- printf("please input the first letter of someday!\n");
- break;
- case 's':
- printf("please input the second letter of someday!\n");
- if ((ch = getchar()) == 'a')
- printf("saturday\n");
- else if (ch == 'u')
- printf("sunday\n");
- else
- printf("input error!!!\n");
- printf("please input the first letter of someday!\n");
- break;
- }
- }
-
- return 0;
- }
复制代码 写代码,至少用 C11 的标准,int main() return 0;
多重输入还是用 scanf() 或者 scanf_s()比较安全。问题与输入缓冲区有关,所以前面 fflush(stdin) 把缓冲区清空。 if () else if() 是连续的,会执行 if() 的条件判断,如果不符合,执行下一个 else if() 的判断。
getchar() 返回当前指针指向缓冲区的字符,然后指针完后移动。你输入的只有单一字符,所以下一个是回车。你用两个 getchar() 就指向换行了。
getchar() 的功能不是要求输入,而是从输入缓冲区里提出一个元素。 |
|