我可以在switch语句中包含cin吗?
Can I include cin within a switch statment
我正在编写一个程序,将给出一个形状的面积,我必须创建一个菜单,让用户选择使用开关的形状。所以我的问题是,我可以有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;
}
case 1: cout << "Radius? "<<;
在"Radius?"
之后有一个流浪的<<
可以在switch语句的case后面包含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;
}
您可以使用enum填充并切换:
#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;
}
当然可以在switch语句中使用cin。没有这样的界限。由于代码中有许多其他语法错误的语句,因此会出现错误。检查@Franck的答案,因为他已经纠正了他们。如果你想了解更多关于Switch语句的信息。这些都是很好的参考资料。
https://www.tutorialspoint.com/cprogramming/switch_statement_in_c.htm http://www.programiz.com/cpp-programming/switch-case相关文章:
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 编译包含字符串的代码时遇到问题
- c++库的公共头文件中应该包含什么
- 将包含C样式数组的对象初始化为成员变量(C++)
- 是否需要删除包含对象的"pair"?
- C++中的cin.ignore()函数不适用于整个流
- 函数何时会在c++中包含stack_Unwind_Resume调用
- 如何将包含epoch时间的十六进制字符串转换为time_t
- 使用mongocxx驱动程序时包含头文件问题
- 如何在h文件中包含.o对象文件
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- Problems with std::cin.fail()
- 为什么我必须在包含后写 std::cin <iostream>?
- 如何处理包含空格的 cin 的用户输入?
- 为什么 cin 在包含字符串标头后接受字符串输入
- 如何检查 cin 缓冲区是否包含相同的值 0.5 秒 (C++)
- 如果 cin 在字符串之前包含整数,则出现打印错误
- 我可以在switch语句中包含cin吗?
- 为什么在我包含 cin.get() 后控制台关闭?