如何修复当 switch 语句处于 while 循环中时不断发生的无限循环
How to fix an infinite loop that keeps occurring in when a switch statement is in a while loop
我是 c++ 的新手,对于一项作业,我有一个程序需要在一段时间内切换,但我总是陷入无限循环
我尝试过寻找解决方法,但由于我不擅长c ++,所以我真的很难得到我的错误
#include <iostream>
#include <stdio.h>
using namespace std;
int main(void)
{
float length, width, perimeter, area;
char ans;
cout<<"Please enter the length of the rectangle: n";
cin>>length;
cout<<"Please enter the width of the rectangle: n";
cin>>width;
cout<<"What do you wish to do with these values?n";
cout<<"Choose an option from the menu: n";
cout<<"1 - Calculate Perimetern";
cout<<"2 - Calculate Arean";
cout<<"3 - Quitn";
cout<<"Please enter your choice: n";
cin>>ans;
while (ans != '3')
{
printf("give option: "); //found this online
ans = getchar(); //this too
switch (ans)
{
case '1' :
perimeter=2*(length+width);
cout<<"The perimeter of the rectangle with length "<<length<<" and width "<<width<<" is "<<perimeter<<endl;
break;
case '2' :
area=length*width;
cout<<"The area of the rectangle with length "<<length<<" and width "<<width<<" is "<<area<<endl;
break;
default :
cout<<"Invalid Entry, please only select options from menu"<<endl;
}
}
printf("Program finished...n"); //this was online too
return 0;
}
当我输入选项 2 或 1 时,有一个无限循环,我似乎无法解决这个问题。我不习惯在这个网站上格式化,请原谅我格式化代码的方式
getchar()
不是在那里使用的正确函数。它返回所有字符、空格、换行符等。
如果添加一行以在此之后立即输出ans
的值,则会注意到分配给ans
的所有值。
ans = getchar();
cout << "answers: " << (int)ans << endl;
要跳过流中的空格,请使用
cin >> ans;
此外,在while
循环中获取ans
的逻辑存在缺陷。它应该在switch
声明之后。否则,程序会在第一次执行 switch
语句之前尝试读取ans
两次。
这是对我有用的相关代码的更新版本。
cout << "Please enter your choice: n";
cin >> ans;
while (ans != '3')
{
switch (ans)
{
case '1' :
perimeter=2*(length+width);
cout<<"The perimeter of the rectangle with length "<<length<<" and width "<<width<<" is "<<perimeter<<endl;
break;
case '2' :
area=length*width;
cout<<"The area of the rectangle with length "<<length<<" and width "<<width<<" is "<<area<<endl;
break;
default :
cout<<"Invalid Entry, please only select options from menu"<<endl;
}
cout << "Please enter your choice: n";
cin >> ans;
}
以下是
有关格式化的一些帮助 https://stackoverflow.com/editing-help:将代码块的整个代码 4 个空格缩进到右侧。当您继续编写问题时,您还必须能够看到下面的预览。
getchar(( 不是在这里使用的合适函数。在这里阅读细微差别:http://www.cplusplus.com/forum/general/193480/
CIN将更适合使用。
此外,逐步分析您的代码。你在 while 循环外面有一个输入线,还有一个在里面。意识到为什么这是错误的,并尝试修复它。
由于这是一个作业问题,我不会告诉你答案,但希望能引导你了解你哪里出错了。
解决问题后,请返回并分析原始代码不起作用的原因。它非常有帮助。
相关文章:
- 有没有办法重复循环循环?
- 无限而循环不工作C++
- 我在C 初学者中发现了无限的循环问题
- 谁能告诉我为什么我的程序在无限的循环中进行
- 虽然第三次循环循环,尽管在我眼中没有满足它的条件,因此打印了一个空字符串
- 避免以不同的迭代剂的循环循环避免几乎相同的代码重复
- 为什么这条线是无限的循环
- 我得到一个无限的循环,我不确定为什么或如何修复它
- C 更改了与循环无关的东西后,卡在无限的循环中
- 为什么我有这个无限的循环
- 试图打破一段循环时,卡在无限的循环中
- 如何通过在Qt中按esc来摆脱无限while循环
- 我的声明是无限的循环
- 无限 while 循环 - 字符关闭不起作用C++
- 无限 while 循环在要求用户输入 2 个数字时发生
- 在无限 while 循环中调用 Sleep() 有多重要
- C++:布尔表达式导致无限 while 循环
- 读取所有数据后进行无限cin循环
- 如何修复一个无限while循环
- C字符串无限For循环的小C[]