cin.get(char) + switch statement

Hey everyone,

I am currently struggeling with using the get function of the standard input stream. I want to use an endless while loop to get user input that breaks in case the user has no more input. further, in some cases i want to process what comes after the initial input char. e.g. with input "n 34 22" i need n as a char to determine the case in a switch statement and 34 and 22 as simple outputs. for the following code my questions are:

can i use .get(char) to extract the 'no more input' scenario (was suggested in the exercise)?

in input i want to distinguish between simple whitespaces and an actual 'wrong' input (all those inputs that are not specified as cases). with input "n 32 22" the output will be "32 22 \n" "DEFAULT CASE\n". with 5 whitespaces, i will get 5 x "DEFAULT CASE\n". I feel my problem is using cin,get correctly. I have no prior C experience, which may complicate things.

Here is the Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include<iostream>

using namespace std;
int main()
{

  while(true)
  {
    cout << "? ";
    char ch;
    
    if(!cin.get(ch)) break;
    
    switch(ch)
    {
    case 'q' : return 0;
    case 'n' : int v1, v2;
                cin >> v1 >> v2;
                cout << v1 << " " << v2 << '\n';
                break;
    case '*' : char v3;
                cin >> v3;
                cout << (int)v3 << '\n';
                break;                  
    case 'i' : cout << 'i'<< '\n';
                break;
    default  : cout << "DEFAULT CASE \n";
    }
        
  }

}


Thanks in advance for any tips hints and suggestions!
If you don't want to read the spaces, then don't read them.
If you want to threat them differently, then make a especial case for them.
ok
You need to place brackets around each of your cases (this is good practice in general anyways). It is particularly important here because you're declaring variables within these cases which, without brackets, have the switch statement's scope (not the case's "scope" because cases are only labels and do not have their own scope).

get() will only retrieve one character each time and that character is treated as char. If you want to be able to process various possible inputs like:
1
2
3
n 36 99
i
* 55

You can store the entire user input into a string and parse it to determine how much input the user did, storing 'n', '36', '99' into variables that can be used in the switch and handle user input errors (before the switch statement).
Topic archived. No new replies allowed.