gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 04:21:40 25 4
gpt4 key购买 nike

我是 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 时,有一个无限循环,我似乎无法解决这个问题。我不习惯在这个网站上格式化,请原谅我格式化代码的方式

最佳答案

getchar() 不是在那里使用的正确函数。它返回所有字符、空格、换行符等。

如果紧接着添加一行输出 ans 的值,您会注意到分配给 ans 的所有值。

ans = getchar();
cout << "ans: " << (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;
}

关于c++ - 如何修复 switch 语句处于 while 循环时不断发生的无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55320124/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com