【发布时间】:2017-09-05 06:51:40
【问题描述】:
我正在创建一个程序,它会询问用户回复以及您想要打印回复并显示多少次。我在程序中使用了一个while循环和switch case。
但是当我在std::cin 的帮助下将输入存储在变量a 中时,switch case 不会接收到相同的输入。任何帮助表示赞赏。
#include <iostream>
using namespace std;
int a;
int input;
int i=1;
void display()
{
cout << "Select a choice for reply" << endl;
cout << "1.Thank You" << endl;
cout << "2.Welcome" << endl;
cout << "3.Okay" << endl;
}
int main()
{
display();
cout << "Enter Choice" << endl;
cin >> a;
input='a';
switch (input)
{
case '1': {
int x;
cout << "Enter no. of times you want to print reply line" << endl;
cin >> x;
while (i <= x)
{
cout << "Thank you" << endl;
}
break;
}
case '2': {
int x;
cout << "Enter no. of times you want to print line" << endl;
cin >> x;
while (i <= x)
{
cout << "Welcome" << endl;
}
break;
}
case '3': {
int x;
cout << "Enter no. of times you want to print line" << endl;
cin >> x;
while (i <= x)
{
cout << "okay" << endl;
}
break;
}
default: {
cout << "wrong choice" << endl;
}
cout << "Thank you for replying" << endl;
}
return 0;
}
【问题讨论】:
-
case '1'- 嗯。对你有用的机会很小。我不认为您尝试过case 1(即不要使用字符文字)。而且由于在随后的while循环中i和x都没有改变,即使你解决了第一个问题,它也注定会旋转到无穷大。我强烈建议good book on C++。 -
请正确格式化您的代码,就像您的 C++ 教科书中的示例一样。
-
您将
input声明为integer,然后分配了input='a'。之后你输入switch(input)。 -
编译所有警告和调试信息(例如
g++ -Wall -Wextra -g和GCC...)然后使用调试器 (gdb) -
我认为您将数字 (
'9') 与数字 (9) 混淆了。
标签: c++ switch-statement cin