如何解决在switch语句处于while循环中时不断发生的无限循环

时间:2019-03-24 02:07:40

标签: c++

我是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 Perimeter\n";
   cout<<"2 - Calculate Area\n";
   cout<<"3 - Quit\n";
   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时,出现无限循环,我似乎无法解决。 我不习惯在此网站上进行格式化,请原谅我格式化代码的方式

2 个答案:

答案 0 :(得分:1)

getchar()不是在此处使用的正确功能。它返回所有字符,空格,换行符等。

如果之后添加一行以输出ans的值,您会注意到分配给ans的所有值。

ans = getchar();
cout << "ans: " << (int)ans << endl;

要从流中跳过空格,请使用

cin >> ans;

此外,在ans循环中获取while的逻辑是有缺陷的。应该在switch语句之后。否则,您的程序将在第一次执行ans语句之前尝试两次读取switch

这是对我有用的相关代码的更新版本。

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;
}

答案 1 :(得分:0)

以下是有关格式化的一些帮助:https://stackoverflow.com/editing-help。 在代码块的右边向右缩进整个代码4个空格。 继续编写问题,您还必须能够在下面看到预览。

getchar()不适用于此处。在这里了解细微差别:http://www.cplusplus.com/forum/general/193480/

cin将更适合使用。

此外,请逐步分析您的代码。您在while循环之外有一条输入行,在里面也有一条输入行。了解为什么这是错误的,然后尝试修复它。

由于这是一个分配问题,所以我不会告诉您答案,但希望可以使您了解您要去哪里。

解决问题后,请返回并分析为什么原始代码不起作用。它极大地帮助了。