C++ 用字符串回显用户输入
我的程序应该显示请求形状的名称。我不习惯使用字符串,那么我如何回显用户的输入(C显示圆锥体等)?我在猜测某种if语句,但不确定如何编写它 样本:C++ 用字符串回显用户输入,c++,codeblocks,C++,Codeblocks,我的程序应该显示请求形状的名称。我不习惯使用字符串,那么我如何回显用户的输入(C显示圆锥体等)?我在猜测某种if语句,但不确定如何编写它 样本: Hello. Welcome to the shape volume computing program. Which shape do you have? (C for cone, U for cube, Y, for cylinder P for pyramid, S for sphere, or Q to quit)
Hello. Welcome to the shape volume computing program.
Which shape do you have? (C for cone, U for cube, Y, for cylinder P for pyramid, S for sphere, or Q to quit)
Enter shape: U
okay, cube. Please enter the length of a side: 3
okay, the length of the side = 3
the volume = 27
enter shape: C
okay, cone. Please enter the radius of the base: 2
please enter the height: 3
okay, the radius = 2 and the height = 3
the volume = 12.56
enter shape: Q
bye!
代码:
intmain()
{
字符串C、U、Y、P、S;
C=“锥体”;
U=“立方体”;
Y=“气缸”;
P=“金字塔”;
S=“球体”;
int Q=-1;
这句话怎么说
cin>> C,U,Y,P,S,Q;
意味着
因为逗号运算符在所有运算符中优先级最低
因此,它将一个字符输入到C
,然后(这是逗号运算符所做的)计算U
、Y
、p
、S
和Q
,后者的值作为表达式结果,然后将其丢弃
那可能不是你想象的那样
为了让这一切顺利,你可以
- 使用单个输入变量,例如称为
line
- 使用
标题中的getline
功能输入一行
- 检查输入行是否为“U”
,在这种情况下执行U操作,或者其他字母,在这种情况下执行其他操作。if
语句适用于此
此代码错误
cin >> C,U,Y,P,S,Q;
这将尝试将用户键入的任何内容写入C指向的内存中。其他逗号分隔的部分是没有效果的单独语句
您要做的是将用户的输入写入一个新变量
char choice;
cin >> choice;
然后看看这是什么,并作出相应的反应
if ('C' == choice)
{
// print output
}
else if ('U' == choice)
{
// print output
我可以告诉你,你的if语句是给Q分配的。是的,在这种情况下应该这样做。至少阅读C++入门的前几章是个好主意:我需要的正是:
char choice;
cin >> choice;
if ('C' == choice)
{
// print output
}
else if ('U' == choice)
{
// print output