0

I just want to read sign character from user and after this ask whether he/she wants to repeat.

it is something like this:

cout << "Please now enter the sign (+-*/): ";
        cin >> *sign;
        cout <<endl; 

and after some time:

cout << "Do you want to try again? (y - yes, anything else - no): ";
        cin >> *yn;

problem is that if user enters something like "+t" in the first time then 't' is automatically assigned to the second yn character.

So how I can prevent this?

Yksisarvinen
  • 18,008
  • 2
  • 24
  • 52

2 Answers2

0

You have two options:

  1. Read only one character from std::cin (example)
  2. Process only the first character character, i.e., sign[0]
Victor
  • 460
  • 3
  • 11
0

I will assume sign and yn are of type char* since you didn't specify it.

What would happen in that case is that the input stream would give one char to *sign and keep the remainder of the input for the next access to the stream. So what you need to do is flush it. You can do that by calling ignore on the stream with std::numeric_limits<std::streamsize>::max() and '\n' as arguments, like that:

#include <iostream>
#include <limits> //For std::numeric_limits<std::streamsize>::max()

int main()
{
    char* sign = new char;
    char* yn = new char;

    std::cout << "Please now enter the sign (+-*/): ";
    std::cin >> *sign;
    std::cout << std::endl; //This std::cout is useless, entering an input in std::cin already returns to a newline

    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //Like this

    std::cout << "Do you want to try again? (y - yes, anything else - no): ";
    std::cin >> *yn;

    std::cout << *sign << std::endl << *yn << std::endl;
    
    delete sign;
    delete yn;
}

The first argument tells ignore how many char to extract from the stream while the second tells it when to stop extracting.

Here is a link to the cppreference page about ignore

Zatmos
  • 16
  • 1
  • 4
  • Wow thanks, really appriciate that. I don't understand this line: ```std::cin.ignore(std::numeric_limits::max(), '\n')``` but I will try to dig into it and analyze. Thanks again – Andro Mazmishvili Jan 29 '21 at 10:49
  • @AndroMazmishvili Basically, std::cin is a stream. A stream is an object that can be written to or read from and stores what is written until it is read. If you don't read it entirely, like by just reading a `char` from it when multiple `char` were written to it, it will still have things stored inside the stream and the next time you will want to read, it will give you what was still stored inside. So you need to erase the stream's content which is what `ignore` does. `std::numeric_limits::max()` is just a number representing the maximum number or `char` inside a stream. – Zatmos Jan 29 '21 at 11:05
  • ohh clear, I get it now, excelent explanation – Andro Mazmishvili Jan 29 '21 at 15:07