使用Switch C ++从用户获取输入 [英] Getting input from user with Switch C++

查看:311
本文介绍了使用Switch C ++从用户获取输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个系统,用户可以输入他/她想要的输入,并进行一些计算。

I have a system where user can enter as many inputs as s/he wants and make some calculations.

这是实现这个任务的代码: p>

Here is the code for achieving this task:

int main() {
    char op = 's';
    float time=0, fuel_rate=0, start=0, end=0, pace=0;


    while(op != 'x'){
        cout << "Please select: " << endl;
        cout << "1 ---> A" << endl;
        cout << "2 ---> B" << endl;
        cout << "3 ---> Calculate" << endl;
        cout << "x ---> Exit" << endl;

        op = std::getchar();

        //remove the rest of the line from input stream
        int temp;
        while ( (temp = std::getchar()) != '\n' && temp != EOF );

        switch(op){
        case '1':
            cout << "Enter time: ";
            cin >> time;
            cout << "Enter fuel rate: ";
            cin >> fuel_rate;
            break;
        case '2':
            cout << "Enter start: ";
            cin >> start;
            cout << "Enter end: ";
            cin >> end;
            cout << "Enter pace: ";
            cin >> pace;
            cout << "Enter fuel rate: ";
            cin >> fuel_rate;
            break;
        case '3':
            cout << "Total value";
            break;
        case 'x':
            return 0;
        default:
            continue;
        }
    }
    return 0;
}

系统适用于第一个输入。示例控制台日志如下所示:

System works well for the first input. Sample console log looks like this:

 Please select: 
1 ---> A
2 ---> B
3 ---> Calculate
x ---> Exit
1
Enter time: 2
Enter fuel rate: 3
Please select: 
1 ---> A
2 ---> B
3 ---> Calculate
x ---> Exit
2
Please select: 
1 ---> A
2 ---> B
3 ---> Calculate
x ---> Exit

第一个用户输入操作1,系统询问时间和燃油率。当用户进入操作2时,系统不要求开始,结束或步速。

First user enters the operation 1, system asks for time and fuel rate. When user enters the operation 2, system doesn't ask for start, end or pace.

有关如何解决这个问题的任何建议吗?

Any ideas on how to solve this?

推荐答案

相当肯定 std :: getchar()是大多数问题的原因。如果我将您的代码更改为使用:

I am fairly certain std::getchar() is the cause of most of your problems. If I change your code to use:

cin >> op;
switch (op) { 
//...

/ p>

Instead of

op = std::getchar();

//remove the rest of the line from input stream
int temp;
while ( (temp = std::getchar()) != '\n' && temp != EOF );

switch(op){
//...

程序运行正常。

这篇关于使用Switch C ++从用户获取输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆