1
char Oprt;
cout << "\nPlease enter first number: ";
cin >> num1;
cout << "Please enter second number: ";
cin >> num2;
cout << "Now please enter operator: ";
cin >> Oprt;
while (Oprt != '+' && Oprt != '-' && Oprt != '*' && Oprt != '/')
{
    cout << "Wrong Operator please enter again: ";
    cin >> Oprt;
}

When user writes something like 'ffsd' as input the loop cycles for as much times as there are characters written by user but what I want is my program to read only first symbol and ignore the rest.

1
  • 2
    I don't really think the "game-engine" tag is relevant. Commented Mar 20, 2017 at 16:31

2 Answers 2

3

You have two valid approaches here:

  • Use cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n') to ignore all characters up to and including '\n', or
  • Use istream::getline to read a whole std::string, and then grab the initial character if the string is not empty.

In both cases you need to ignore the '\n' before entering the loop, because cin >> num2 does not remove '\n' from the input stream.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use std::istream::ignore. For example, like that.

std::cin.ignore(MAX_INPUT_LENGTH,'\n');

For more info, look in the reference

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.