C++ for循环和switch语句逻辑错误
在此循环中(假设 amount
为 2),不是打印:而是
1. [op1]
2. [op2]
打印:
1. [op1]
2. [op2]
3. [op3]
4. [op4]
5. [op5]
Why?我该如何解决这个问题?
for(int i=1;i<=amount;i++){
//string s;
switch(i){
case 1:
cout << i << ". " << op1 << endl;
//s = op1;
case 2:
cout << i << ". " << op2 << endl;
//s = op2;
case 3:
cout << i << ". " << op3 << endl;
//s = op3;
case 4:
cout << i << ". " << op4 << endl;
//s = op4;
case 5:
cout << i << ". " << op5 << endl;
//s = op5;
}
//cout << i << ". " << s << endl;
}
In this loop (assuming amount
is 2), instead of printing:
1. [op1]
2. [op2]
it prints:
1. [op1]
2. [op2]
3. [op3]
4. [op4]
5. [op5]
Why? How can I fix this?
for(int i=1;i<=amount;i++){
//string s;
switch(i){
case 1:
cout << i << ". " << op1 << endl;
//s = op1;
case 2:
cout << i << ". " << op2 << endl;
//s = op2;
case 3:
cout << i << ". " << op3 << endl;
//s = op3;
case 4:
cout << i << ". " << op4 << endl;
//s = op4;
case 5:
cout << i << ". " << op5 << endl;
//s = op5;
}
//cout << i << ". " << s << endl;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要使用
break;
或switch()
来实现所谓的“fallthrough”
。(这意味着它执行您的 case: 然后继续执行随后发生的任何事情,包括其他 case 语句中的代码)。
You need to use
break;
orswitch()
will have what's called"fallthrough"
.(This means that it executes your case: and then continues on anything that comes afterwards, including code in other case statements).
您需要将其放在
每个案例的末尾。否则,它将转到 case1,然后继续直到选择结束。 (案例1、2、3、4、5)
You need to put
at the end of each case. Otherwise it goes to case1, and then continues through to the end of the select. (case1, 2, 3, 4, 5)
您必须在每个
case:
部分的末尾插入break;
语句。这是因为
switch () {}
只是goto
的重新表述,这些情况只是标签,而不是真正的块(这就是为什么他们使用标签语法而不是像case ... { }
这样的块语法。You have to insert
break;
-statements at the end of each of yourcase:
-parts.This is because
switch () {}
is merely a reformulation of agoto
, the cases are just labels, not real blocks (that's why they use the label-syntax instead of a block-syntax likecase ... { }
.在案例后面放置一个“break”语句,否则控制流将直接通过。
Put a "break" statement after the cases, otherwise the control flow will just go straight through.