FGOG
FGOG

Reputation: 15

How can I receive one OR two input?

For example, I make a menu like this:

  1. stack push

  2. stack pop

  3. stack print

Then, if I want to push 5 to the stack, I will type 1 5. But if I just want to pop or print the stack, I will just type 2 or 3.

How can I handle those types? Now I can just receive cin>>i or cin>>i>>n, not both.

Upvotes: 0

Views: 38

Answers (2)

Acha Bill
Acha Bill

Reputation: 1255

You have to process the individually.

int a;
std::cin >> a;
if(a == 1) //push
{
    int b;
    std::cin >> b;
    push(b);
}
else if(a == 2) { pop();}
else if(a == 3) { print(); }
else { std::cout << "invalid" << std::endl; }

Upvotes: 1

NHDaly
NHDaly

Reputation: 8056

You can just write code to decide how much to read based on the situation!

If you know you will always only expect a number with the "stack push" command, only check for the extra number once you read the command.

It could look something like:

cin >> command;
if (command == 1) {
  int value;
  cin >> value;
  ...
} else {
  ...
}

Upvotes: 1

Related Questions