【发布时间】:2015-08-13 18:06:41
【问题描述】:
因此,当我在练习 switch-case 块的变体时,我想尝试循环程序的 Switch-Case 部分,到目前为止我在试验中无法做到这一点。
- 我尝试使用 continue,除非 switch-case 块在循环内,否则它不起作用。
- 我尝试设计一个带条件的 while 循环,但效果并不准确,因为它不会执行 Cases 内的块,并且会简单地跳出 switch 并成功终止程序而不执行 case。
- 我尝试了 goto,但似乎对要使用的标签有一定的规则,目前不赞成在 Switch 中使用 goto。
我的研究仅显示人们在外部循环 Switch-Case(例如在 while 循环或 for 循环中的 Switch-Case 等),但找不到任何人试图从 Switch-Case 块内构建循环的示例的代码。 我不介意解决方案是从头开始重复代码还是再次从 Switch-Case 外部的外部点开始,但目的是让程序以某种方式重新执行 Switch-Case 而无需将同一个 Switch-Case 包含在一个循环。 很长一段时间后,我再次学习 C 编程,因此我确实为此做了很长时间的搜索,但找不到合适的结果。也许我在很长一段时间后也在进行长时间的搜索,所以我可能失去了联系。 有一个类似的问题,但用户给出并接受的解决方案表明与我在这里要求的不同。题 : C programming do while with switch case program
这是我的代码:-
#include <stdio.h>
int main()
{
int input;
printf( "4. Play game\n" ); //i have re-edited the question and shortened the code and included what I additionally tried as per the advice, to focus on the question more, w/o changing the main question .
printf( "Selection: " );
scanf( "%d", &input );
switch ( input )
{
case 4:
printf( "Thanks for playing! Taaaa\n" );
break;
default:
while(input!=4) //just a sample condition, and i know that it doesnt check for letters or characters as input, but that is not the point. I just want to see if a solution on similar thought/methodology exists.
{
printf( "no u have to give a correct input\n" );
scanf("%d", &input);
continue; // I tried a Goto and return; in this loop as well only to realize that it will not jump me out of this loop and back into the program.
}
}
return 0;
}
或者,我可以对我使用的 while 循环做些什么,它工作不准确,但没有错误或警告。如前所述,while 循环没有执行 case 内的块,但它刚刚爆发了。
输出图片:
【问题讨论】:
-
您的代码并没有真正检查正确的输入,尝试输入
asdasd并且会出现未定义的行为。另外,你为什么要那样做? -
是的,我知道我尝试输入了一个字母,是的,它进入了无限期打印。但这不是重点.. 这是我可以重新设计和纠正的东西,只有在我首先弄清楚我正在寻找的这个基本东西是否可能之后。无论如何感谢您的说明。顺便说一句,我的问题是错误的,它立即收到了负面标记
-
不是很清楚,而且你要求的东西没人会尝试做,所以我很好奇你为什么这样做?
-
您的问题被否决了,因为它充其量很难理解您要做什么。根本不清楚你的意思。您的示例代码中没有任何循环。
switch语句不打算成为循环;试图滥用它使其像循环一样工作是不明智的。但是你应该停止专注于你正在使用的技术并解释你想要做什么。从表面上看,一个普通的while循环在条件中调用一个输入函数并对返回值做出适当的反应,就可以满足您的需要。 -
@我很担心,因为 stackoverflow 是一个很好的澄清资源,我不希望我的帐户被禁止或禁止提问
标签: c loops while-loop switch-statement