如果用户按'y'或'Y',则运行循环

时间:2014-05-11 16:04:40

标签: c

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

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]$

4 个答案:

答案 0 :(得分:2)

而不是:

scanf("%c",&c);

使用:

scanf(" %c",&c);

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

答案 1 :(得分:1)

您需要考虑新的行字符等。

所以scanf应该只吃它们

答案 2 :(得分:1)

转换说明符"%c"不会忽略空格。因此,当您键入“Y”时,“Y”和“”都会分配给c

您有几种选择:

  1. 使用fgets()获取用户输入
  2. 忽略空白
  3. 使用1-char字符串(char onechar[2];)和转化说明符"%1s"scanf()自动忽略前导空格

答案 3 :(得分:0)

#include <stdio.h>
#include <ctype.h> // to use tolower()


void display_menu(void);


void display_menu()
{
 char c;

  /* char c = 'y'; You don't need to set it equal to y. 
     The do-while loop will run at least one time regardless of you condition */

  printf("This is Menu for Single Linkd List:\n");

 do
 {
    printf("Press 1 for Create Link List \n");
    printf("Press 2 for Insert Node\n");
    printf("Press 3 for Delete the entire list\n");
    printf("Press 4 for Delete the Node\n");
    printf("Press 5 for Reverse the List\n");
    printf("Press 6 for Display the List\n");
    printf("Press 7 for Display the Node\n");
    printf("Press 'y' or 'Y' for Display the Menu again \n");

    scanf(" %c",&c);
    c = tolower(c); //simplifies you while condition.
 }while( c == 'y');

}



int main()
{
 display_menu();

 return 0;
}