C 中的 switch 函数可以处理所有情况 [英] Switch function in C does all the cases

查看:37
本文介绍了C 中的 switch 函数可以处理所有情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我正在为某事编写代码,但在测试 switch 功能时遇到了问题.它执行从一个人的选择(我的解释)递增的所有情况.有人能帮我解释一下为什么会这样吗?

Okay so I'm writing a code for something and I've encountered a problem whilst testing switch function. It does all the cases incrementing from one's selection (my explanation). Could someone help me explain why is this so?

#include <stdio.h>
#include <stdlib.h>
#include "ratedzfunctions.h"

int main()
{

    int selection, loop=1;
    FILE* fajl;

    //Opening the participants file
    fajl=fopen("participants.txt","r+");
    if (fajl==NULL)
    {
        printf("The file cannot be opened.\n");
    }

    //MENU
    do 
    {
        printf("\nMENU: \n------------\n1. RATEDZ\n\n2. STATISTICS\n\n3. EXIT\n\n==>");
        scanf("%d", &selection);

        switch (selection)
        {
        case 1:
            ratedz(fajl);
        case 2:
            stats(fajl);
        case 3:
            loop=0;
        }
    }

    while (loop==1);

    fclose(fajl);

    return 0;
}

//THIS IS FROM RATEDZFUNCTIONS.H

void ratedz(FILE *fajl)
{
    printf("\nTEST RATEDZ");
}

void stats(FILE *fajl)
{
    //Printing all participants
    char *buffer=(char*) malloc(50);

    while(fscanf(fajl,"%s %s %s", buffer)!=EOF)
    {
        printf("\n%s %s %s", buffer);
    }

    free(buffer);
}

推荐答案

你应该在每个 case 后面放一个 break;.

You should put a break; after each case.

switch/case 规则很简单,在一个 mached case 之后,接下来的所有 case 都会被执行,直到 break;switch 结束>:

The switch/case rule is easy, after a mached case, all following cases will be executed until a break; or end of switch:

switch (selection)
{
case 1:
       ...
       break;
case 2:
       ...
       break;
case 3:
       ...
       break; // Last break is not necessary
              // but it's good practice to put it.
}

<小时>

在某些情况下,删除 break; 是合理的:

switch(letter) 
{
case 'i':
case 'a':
case 'o':
case 'u':
case 'e':
           printf ("Vowel!");
           break;
default :
           printf ("Consonant!");
           break;   
}

这篇关于C 中的 switch 函数可以处理所有情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆