0

I am using the flowing code to check if the user entered only numbers.

while(!cin)
  {
    cout << "You entered something that is not a number. Please try again" << endl;
    cout << "Please enter the point on the circle in the form x y: ";
    cin.clear();
    cin.ignore();
    cin >> coordX >> coordY;
    cout << endl;
  }

It works if the user enters "&". The error is it reprints for every non number character that is entered. For example if (4,2) is entered it would print 3 times. How can I make it only print once?

  • 2
    Duplicate: https://stackoverflow.com/questions/24504582/how-to-test-whether-stringstream-operator-has-parsed-a-bad-type-and-skip-it – πάντα ῥεῖ Sep 25 '20 at 21:42
  • Does this answer your question? [How to test whether stringstream operator>> has parsed a bad type and skip it](https://stackoverflow.com/questions/24504582/how-to-test-whether-stringstream-operator-has-parsed-a-bad-type-and-skip-it) – Harry J Sep 26 '20 at 00:42

1 Answers1

1

If you want that kind of input you could get the line from the console with std::getline and then you can divide it with the " " as the delimeter character (this is necessary because we don't know the lengths of the numbers). After That you just have to convert the substrings to integers.

Here is a working example( there are no validity checks but it works)

    #include <iostream>
    int main()
    {
        int coordX, coordY;
    
        std::string input;
        std::getline(std::cin, input);
    
        size_t pos = input.find(" ");
        coordX = std::stoi(input.substr(0, pos));
        coordY = std::stoi(input.substr(pos + 1, input.length()));
        std::cout << "coordX: " << coordX << " coordY: " << coordY;
    }