C 中的 switch 函数适用于所有情况 [英] Switch function in C does all the cases
本文介绍了C 中的 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.
");
}
//MENU
do
{
printf("
MENU:
------------
1. RATEDZ
2. STATISTICS
3. EXIT
==>");
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("
TEST RATEDZ");
}
void stats(FILE *fajl)
{
//Printing all participants
char *buffer=(char*) malloc(50);
while(fscanf(fajl,"%s %s %s", buffer)!=EOF)
{
printf("
%s %s %s", buffer);
}
free(buffer);
}
推荐答案
你应该在每个case
之后放置一个break;
.
You should put a break;
after each case
.
switch/case
规则很简单,在一个匹配的 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屋!
查看全文