C/C++教程

c 语言 限制用户的选项(菜单浏览)

本文主要是介绍c 语言 限制用户的选项(菜单浏览),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

 

1、

#include <stdio.h>

int main(void)
{
    char choice;
    
    printf("a) xxxx    b) yyyy\n");
    printf("c) zzzz    q) quit.\n");
    printf("input your choice: ");
    
    while((choice = getchar()) != 'q')
    {
        switch(choice)
        {
            case 'a': printf("choose a.\n"); break;
            case 'b': printf("choose b.\n"); break;
            case 'c': printf("choose c.\n"); break;
            default: printf("input errer, the range is a b c q\n"); break;    
        }
        while(getchar() != '\n')
            continue;
        printf("\n\na) xxxx    b) yyyy\n");
        printf("c) zzzz    q) quit.\n");
        printf("input your choice: ");
    }    
    
    return 0;
} 

 

 

 

2、

#include <stdio.h>

char get_choice(void);

int main(void)
{
    char choice;
    while((choice = get_choice()) != 'q')
    {
        switch(choice)
        {
            case 'a': printf("you choose a.\n\n"); break;
            case 'b': printf("you choose b.\n\n"); break;
            case 'c': printf("you choose c.\n\n"); break;
            default: printf("grogramm ereor.\n\n"); break;    
        }    
    }    
    
    return 0;
} 

char get_choice(void)
{
    char ch;
    printf("a) xxx    b) yyyy\n");
    printf("c) zzz    q) quit\n");
    printf("your choice: ");
    
    ch = getchar();
    while(getchar() != '\n')
        continue;
    while(ch < 'a' || ch > 'c' && ch != 'q')
    {
        printf("the range is a b c and q, try again: ");
        ch = getchar();
        while(getchar() != '\n')
            continue;
    }

    return ch;
}

 

3、

#include <stdio.h>

char get_choice(void);

int main(void)
{
    char choice;
    while((choice = get_choice()) != 'q')
    {
        switch(choice)
        {
            case 'a': printf("you choose a.\n\n"); break;
            case 'b': printf("you choose b.\n\n"); break;
            case 'c': printf("you choose c.\n\n"); break;
            default: printf("grogramm ereor.\n\n"); break;    
        }    
    }    
    
    return 0;
} 

char first_choice(void);
char get_choice(void)
{
    char ch;
    printf("a) xxx    b) yyyy\n");
    printf("c) zzz    q) quit\n");
    printf("your choice: ");
    
    ch = first_choice();

    while(ch < 'a' || ch > 'c' && ch != 'q')
    {
        printf("the range is a b c and q, try again: ");
        ch = first_choice();

    }

    return ch;
}

char first_choice(void)
{
    char ch;
    
    ch = getchar();
    while(getchar() != '\n')
        continue;
    
    return ch;
}

 

这篇关于c 语言 限制用户的选项(菜单浏览)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!