gpt4 book ai didi

c - 如果用户按下 'y' 或 'Y' 则运行循环

转载 作者:太空宇宙 更新时间:2023-11-04 06:28:07 24 4
gpt4 key购买 nike

在按下“y”或“Y”之前,我无法执行 do while for。请找到我写的代码:: 问题是当我执行这个程序时,第一次显示菜单项并正确处理并等待从用户那里获取输入。第二次也是正确显示菜单,但不等待用户获取输入。相反,它退出了执行。请提供克服此解决方案的解决方案

C 程序:

#include<stdio.h>


void display_menu(void);


void display_menu()
{
char c='y';
printf("\n This is Menu for Single Linkd List");
do
{
printf("\n Press 1 for Create Link List ");
printf("\n Press 2 for Insert Node");
printf("\n Press 3 for Delete the entire list");
printf("\n Press 4 for Delete the Node");
printf("\n Press 5 for Reverse the List");
printf("\n Press 6 for Display the List");
printf("\n Press 7 for Display the Node");
printf("\n Press 'y' or 'Y' for Display the Menu again \n");
if(c=='\n')
c='\0';
scanf("%c",&c);//getchar();
printf("c=%c", c);
}while(c=='y' || c=='Y');

}



int main()
{


display_menu();

return 0;
}

执行输出:

[sambath@localhost exercise]$ ./a.out

This is Menu for Single Linkd List
Press 1 for Create Link List
Press 2 for Insert Node
Press 3 for Delete the entire list
Press 4 for Delete the Node
Press 5 for Reverse the List
Press 6 for Display the List
Press 7 for Display the Node
Press 'y' or 'Y' for Display the Menu again
y
c=y
Press 1 for Create Link List
Press 2 for Insert Node
Press 3 for Delete the entire list
Press 4 for Delete the Node
Press 5 for Reverse the List
Press 6 for Display the List
Press 7 for Display the Node
Press 'y' or 'Y' for Display the Menu again
c=
[sambath@localhost exercise]$

最佳答案

代替:

scanf("%c",&c);

使用:

scanf(" %c",&c);

前导空格告诉 scanf() 在读取下一个字符之前跳过剩余的空白字符(包括 '\n')。

关于c - 如果用户按下 'y' 或 'Y' 则运行循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23594849/

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