我正在写一个程序,将给出一个形状的面积,我必须创建一个菜单,让用户选择一个形状使用开关。所以我的问题是,我可以使用cin和开关情况,或者我必须以不同的方式格式化我的代码。
#include <cmath>
#include <iostream>
#include <cassert>
using namespace std;
int main()
{
int shape, invalid;
double area, radius, width, height;
const double pi=3.14159;
cout << "Shape Menu"<<endl<< "1. Circle"<<endl<<"2. Rectangle"<<endl<<"3. Triangle"<<endl
<<"shape (1, 2, or 3)? ";
cin >> shape;
switch (shape){
case 1: cout << "Radius? "<<;
cin >> radius >> endl;break; // this is were my error is when I compile
case 2: cout << "width? ";
cin >> width >> endl;
cout << "Height? ";
cin >> height >> endl;break;
case 3: cout<< "Base? ";
cin >> base >> endl;
cout << "Height? ";
cin >> height >> endl;break;
default: invalid = shape
cout<< shape << "is an invalid menu option, program terminated."<<endl;
assert (invalid == T)
}
return 0;
}
发布于 2016-10-08 22:20:53
case 1: cout << "Radius? "<<;
你在"Radius?"
之后有一个流浪的<<
发布于 2016-10-08 22:28:50
是的,您可以在switch语句的cases之后包含cin
。像case 1:
这样的案例仅仅是标签。所以后面的指令可以是任何指令。
您的代码有许多编译错误:下面是switch语句的一个可能的替代品。
switch (shape){
case 1: cout << "Radius? ";
cin >> radius;break; // no more error here
case 2: cout << "\nwidth? ";
cin >> width;
cout << "\nHeight? ";
cin >> height;break;
case 3: cout<< "Base? ";
cin >> base;
cout << "\nHeight? ";
cin >> height;break;
default:
invalid = shape;
cout<< shape << "is an invalid menu option, program terminated."<<endl;
}
发布于 2016-10-08 23:00:16
您可以使用枚举和开关进行fullfil:
#include <iostream>
enum SHAPES{CIRCLE = 1, SQUARE, RECTANGLE, TRIANGLE, CUBE};
int main()
{
int choice;
std::cout << "1: Circle 2: Square 3: Rectangle 4: Triangle 5: Cube" << std::endl;
std::cout << " >> ";
std::cin >> choice;
std::cout << std::endl;
switch(choice)
{
case CIRCLE:
{
//do something
}
break;
case SQUARE:
{
//do something
}
break;
case RECTANGLE:
{
//do something
}
break;
case TRIANGLE:
{
//do something
}
break;
case CUBE:
{
//do something
}
break;
default:
std::cout << "Bad Entry!" << std::endl;
}
std::cout << std::endl;
return 0;
}
https://stackoverflow.com/questions/39937944
复制相似问题