我是C ++的新手,对此程序有些困惑。我正在Visual Studio 2008中将此作为win32控制台应用程序运行。

    #include <iomanip>
    #include <cmath>
    #include <string>
    using namespace std;
    #define PI 3.14
    int l=1;
    int x;
    void main()
    {
        do
        {
            cout << "choose 1";
            cout << "choose 2";
            cin >> x;
            switch(x)
            {
                case 1:
                    cout << "action 1";
                    break;
                case 2:
                    cout << "action 2";
                    break;
                default:
                    cout << "unknown command";
                    break;
            }
        } while (l=1)
    }


当我运行该程序并键入1或2以外的任何其他内容时,它未在开关中显示默认选项。我无法找出问题所在。我该如何解决这个问题?

最佳答案

这是更好的第一次尝试,它确实会根据输入执行所有三种情况。由于各种错误,您提供的原始版本甚至没有编译。

我建议您从这一点开始:

#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
using namespace std;
int main()
{
    int x;
    do
    {
        cout<<"choose 1 or 2: ";
        cin>>x;
        switch(x)
        {
            case 1:
                cout<<"action 1"<<endl;
                break;
            case 2:
                cout<<"action 2"<<endl;
                break;
            default:
                cout<<"unknown command"<<endl;
                break;
        }
    } while(1==1);
    return 0;
}


这是一个示例运行:

choose 1 or 2: 1
action 1
choose 1 or 2: 2
action 2
choose 1 or 2: 3
unknown command
choose 1 or 2: ^C


即使使用固定代码也仍然存在问题,例如输入非数字时。您确实应该从标准输入中获取字符串,并在转换为数字之前检查其有效性。

要处理非数字,这将是一个不错的开始:

#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
using namespace std;
int main()
{
    string x;
    do
    {
        cout<<"choose 1 or 2: ";
        cin>>x;
        if (!isdigit(x[0])) {
            cout<<"non-numeric command"<<endl;
        } else {
            switch(x[0])
            {
                case '1':
                    cout<<"action 1"<<endl;
                    break;
                case '2':
                    cout<<"action 2"<<endl;
                    break;
                default:
                    cout<<"unknown command"<<endl;
                    break;
           }
       }
    } while(1==1);
    return 0;
}

07-24 09:44
查看更多