如何修复当 switch 语句处于 while 循环中时不断发生的无限循环

How to fix an infinite loop that keeps occurring in when a switch statement is in a while loop

本文关键字:无限循环 循环 switch 何修复 语句 while      更新时间:2023-10-16

我是 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 循环外面有一个输入线,还有一个在里面。意识到为什么这是错误的,并尝试修复它。

由于这是一个作业问题,我不会告诉你答案,但希望能引导你了解你哪里出错了。

解决问题后,请返回并分析原始代码不起作用的原因。它非常有帮助。