0

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)

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
user3517150
  • 33
  • 1
  • 1
  • 7
  • Possible duplicate: http://stackoverflow.com/questions/421860/c-c-capture-characters-from-standard-input-without-waiting-for-enter-to-be-pr – Excelcius Apr 14 '14 at 18:52
  • You can read one character from the console, this has been answered many times already. But if the user is going to press enter after `p 3 100` anyway, why not parse the input and look for further arguments in case the string starts with `p`? You will need a condition one way or another. – Excelcius Apr 14 '14 at 18:54
  • If I parse, I have to declare it as char input[]; instead of char input; correct? – user3517150 Apr 14 '14 at 19:02
  • `char input[]` won't work because it has no size (you will get a compiler error). You can use `char input[20]` or some other length to get a static array where the input is stored. This will fail however if there is more input than you specified. The C++ way to do this is to use `std::string input`. – Excelcius Apr 15 '14 at 04:44

2 Answers2

3

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.
}
Raydel Miranda
  • 13,825
  • 3
  • 38
  • 60
0

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);
}
Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154