user3517150
user3517150

Reputation: 33

How to take different types of input in c++

In a program I'm working on, I normally scan for 1 character input, (w,a,s,d)

cin >> input;

But I want to make it so that if the user enters 'p', for example, to further allow him to enter 2 more values.

for example, entering 'a' will move left. But entering 'p 3 100' will place the number 100 in array position 3.

Id prefer that I dont have to press enter after inputting p, because that just means add another condition statement for if (input==p)

Upvotes: 0

Views: 1982

Answers (2)

Raydel Miranda
Raydel Miranda

Reputation: 14360

I recommend you to keep it simple:

Just keep checking for only one character and, if the given character is p then ask for the other arguments to the user.

For instance:

EDIT Code edited to match exactly OP requirements.

char option;
cout << "Enter option: ";
cin >> option;

switch (option)
{
    case 'a':
        // Do your things.
        break;

    case 'p':
        int number, position;
        cin >> number;
        cin >> position;
        // Do your things.
        break;
    // Don't forget the default case.
}

Upvotes: 3

Thomas Matthews
Thomas Matthews

Reputation: 57678

You can continue using cin even after you have read the command:

if (input == 'p')  
{
  int number;
  int position;
  cin >> number;
  cin >> position;
  // ...
}

Or if you want it as a function:

std::istream& Position_Command(std::istream& input_stream)
{
  int number;
  int position;
  input_stream >> number;
  input_stream >> position;
  // ...
  return input_stream;
}

// ...
if (input == 'p')
{
  Position_Command(cin);
}

Upvotes: 0

Related Questions