简体   繁体   English

使用Switch C ++从用户获取输入

[英]Getting input from user with Switch C++

I have a system where user can enter as many inputs as s/he wants and make some calculations. 我有一个系统,用户可以根据需要输入尽可能多的输入并进行一些计算。

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

First user enters the operation 1, system asks for time and fuel rate. 第一个用户进入操作1,系统要求时间和燃油费。 When user enters the operation 2, system doesn't ask for start, end or pace. 当用户进入操作2时,系统不要求输入开始,结束或速度。

Any ideas on how to solve this? 关于如何解决这个问题的任何想法?

I am fairly certain std::getchar() is the cause of most of your problems. 我相当确定std::getchar()是大多数问题的原因。 If I change your code to use: 如果我将您的代码更改为使用:

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

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){
//...

The program runs just fine. 该程序运行正常。

You are mixing the use of std::cin and stdin . 您正在混合使用std::cinstdin You should stick with one of the. 您应该坚持其中之一。 Instead of 代替

    op = std::getchar();

use 采用

    op = cin.get();

You should move the lines: 您应该移动以下行:

    int temp;
    while ( (temp = std::getchar()) != '\n' && temp != EOF );

after the end of the switch block, which making sure that you use temp = cin.get() switch块结束之后,请确保使用temp = cin.get()

Unconsumed newline characters are left in the input stream since you are using operator>>() to read data, like: 由于您正在使用operator>>()读取数据,因此输入流中会保留未使用的换行符,例如:

    cin >> fuel_rate;

Adding debugging print code to the default case of your switch shows clearly what is going on: 将调试打印代码添加到交换机的默认情况下,可以清楚地了解发生了什么:

// ...
default:
  cout << "unexpected: " << int(op) << endl;
  continue;
// ...

unexpected: 10 意外:10

The decimal 10 is the newline \\n that is still in the input buffer after you did formatted input using operator>> on std::cin . 使用std::cin上的operator>>格式化输入后,小数点10是换行符\\n仍在输入缓冲区中。

To correct this you could ignore leftover characters (think of what happens when the user doesn't enter a number when you requested one) from the stream up to and including the next newline character, after you did the formatted input: 要更正此问题,您可以在执行格式化输入后,从流中忽略剩余字符(想一想当用户在输入请求时未输入数字时会发生什么),包括下一个换行符:

cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

Or use formatted input (which does the skipping on its own): 或使用格式化的输入(可自行跳过):

cin >> op;

Though you also need to take care of end of file conditions, which your current code fails to do as you see in the example run above. 尽管您还需要注意文件结束条件,但是您的当前代码无法执行上述操作,如您在上面的示例中看到的那样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM