我正在使用 C 语言并编写了以下代码:
1 #include<stdio.h>
2 #define ASK_PROMPT printf("\nDo you want to continue(Y/N):");
3 main()
4 {
5 char main[20], i;
6 start:
7 printf("Please enter your string:\n");
8 gets(main);
9 printf("\nstring entered was:\n \n%s\n", main);
10 ASK_PROMPT;
11 scanf("%c",&i);
12
13 if(i=='Y'||i=='y')
14 goto start;
15 getch();
16 return;
17 }
当我执行此代码时,goto 循环
无法正常工作。在对第 10 行提出的问题提供 y
或 Y
响应时,循环确实有效,并且第 7 行再次执行/打印,但第 8 行被跳过(不等待提供输入)。
- 谁能解释一下为什么会发生这种情况?
- 如何修复它?
最佳答案
我建议不要使用gets
。使用gets
时,如果输入的字符串大于main[的大小怎么办? 20]
.gets
不会阻止这种情况,并且会导致 UB。
使用fgets
-
fgets(main,20,stdin);
问题的原因是 scanf("%c",&i);
之后的 '\n'
仍保留在 stdin
中> 在遇到 '\n'
时导致 gets
返回。
为了避免 '\n'
,您可以在 scanf
语句之后执行此操作 -
int c;
while ( (c = getchar()) != EOF && c != '\n' );
关于c - gets() 函数从第二次开始被跳过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32502613/