C++ primer plus 问题

C++语言 码拜 7年前 (2017-04-24) 1054次浏览
// switch.cpp — using the switch statement
#include <iostream>
using namespace std;
void showmenu();   // function prototypes
void report();
void comfort();
int main()
{
showmenu();
int choice;
cin >> choice;
while (choice != 5)
{
switch(choice)
{
case 1  :   cout << “\a\n”;
break;
case 2  :   report();
break;
case 3  :   cout << “The boss was in all day.\n”;
break;
case 4  :   comfort();
break;
default :   cout << “That”s not a choice.\n”;
}
showmenu();
cin >> choice;
}
cout << “Bye!\n”;
// cin.get();
// cin.get();
return 0;
}
void showmenu()
{
cout << “Please enter 1, 2, 3, 4, or 5:\n”
“1) alarm           2) report\n”
“3) alibi           4) comfort\n”
“5) quit\n”;
}
void report()
{
cout << “It”s been an excellent week for business.\n”
“Sales are up 120%. Expenses are down 35%.\n”;
}
void comfort()
{
cout << “Your employees think you are the finest CEO\n”
“in the industry. The board of directors think\n”
“you are the finest CEO in the industry.\n”;
}
为什么输入字母a后一直循环
C++ primer plus 问题
解决方案

5

int main()
{
    showmenu();
	char str[100];
    int choice;
//    cin >> choice;
    cin.getline(str,sizeof(str)-1);
    choice=atoi(str);
    while (choice != 5)
    {
        switch(choice)
        {
            case 1  :   cout << "\a\n";
                        break;
            case 2  :   report();
                        break;
            case 3  :   cout << "The boss was in all day.\n";
                        break;
            case 4  :   comfort();
                        break;
            default :   cout << "That"s not a choice.\n";
        }
        showmenu();
    	cin.getline(str,sizeof(str)-1);
    	choice=atoi(str);
    }
    cout << "Bye!\n";
    // cin.get();
    // cin.get();
    return 0;
}

3

引用:

本人想知道为什么输入a 会导致一直循环的原因,不是怎么修改代码。

输入 a 会进入一个错误的状态。没有显式的操作会一直处在错误状态,不能继续其它操作。

4

引用:

本人想知道为什么输入a 会导致一直循环的原因,不是怎么修改代码。

原因是输入流被破坏了。

10

http://blog.sina.com.cn/s/blog_8d3652760100wl9r.html

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明C++ primer plus 问题
喜欢 (0)
[1034331897@qq.com]
分享 (0)