#include <iostream>
#include <math.h>
using namespace std;
int main() {
double radius = 0.00;
double height = 0.00;
double width = 0.00;
double side = 0.00;
double Area = 0.00;
const double PI = atan(1.0)*4;
string input = "none";
while (input != "0") {
cout << "Shape Menu: \n (r) rectangle \n (s) square \n (c) circle \n (0) exit" << endl;
cin >> input;
if (input == "r"){
cout << "Please enter a floating point value for the height of the rectangle." << endl;
cin >> height;
cout << height;
while (height <= 0)
{
cin.clear();
cin.ignore(1000, '\n');
cout << "Your input was invalid. Please input a floating point value greater than 0.";
cin >> height;
}
cout << "Please enter a floating point value greater than 0 for the width of the rectangle." << endl;
cin >> width;
while (width <= 0)
{
cin.clear();
cin.ignore(1000, '\n');
cout << "Your input was invalid";
cin >> width;
}
Area = height*width;
cout << "The area of a rectangle with those dimensions is " << Area << "units squared." << endl;
}
else if(input == "s"){
cout << "Please enter a floating point value for the length of the side." << endl;
cin >> side;
if (cin.fail())
cout << "Please enter a floating point value.";
Area = side*side;
cout << "The area of a square with those dimensions is " << Area << "units squared" << endl;
}
else if(input == "c"){
cout << "Please enter a floating point value for the length of the radius." << endl;
cin >> radius;
if (cin.fail())
cout << "Please enter a floating point value.";
Area = radius*radius*PI;
cout << "The area of a circle with those dimensions is " << Area << "units squared." << endl;
}
else if(input == "0"){
break;
}
else{
cout << "Your input does not match one of the options suggested. Please type r, s, c to get the area of a shape, or type 0 to exit." << endl;
}
}
return 0;
}
사용자가 모양 메뉴에서 선택하고 각 유형에 대한 특정 입력을 요구하여 영역을 결정하도록 요청하는 프로그램을 작성하려고합니다. 지금 내가 겪고있는 문제는 사람들이 숫자가 아닌 반지름이나 높이와 너비에 대한 대답을 입력 할 때 오류를 발생시키는 방법을 알아 내려고합니다. 직사각형에 대해 작성하려고 시도한 오류는 초기 부정확 한 입력에 대해 작동했지만 사용자가 다른 모양을 선택하라는 메시지가 나타나면 입력 오류가 다시 발생하면 무한 루프가 시작됩니다.왜 무한 루프가 되는가
오류를 재현하지 못하고 코드가 실제로 복잡합니다. 어쩌면 구두 설명 대신 오류로 연결되는 정확한 입력을 제공 할 수 있습니다. 또한 if (cin >> foo)로 cin에서 읽은 것이 성공했는지 확인하십시오. – pmr