Controlling user input

I am teaching myself C++ to help with upcoming classes that I will be taking at Uni. I am trying to come up with a way to make the program throw an error message if the user tries to input more than two integers into the first prompt. I would appreciate any direction. I want to figure this out with as little help as possible, so please just enough to get me in the right direction.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

using namespace std;

int mult ( int x, int y );

int main()
{
  int x;
  int y;
  
  cout<<"Please input two numbers to be multiplied: ";
  cin>> x >> y;
  cin.ignore();
  cout<<"The product of your two numbers is "<< mult ( x, y ) <<"\n";
  cin.get();
}

int mult ( int x, int y )
{
  return x * y;
}
Read the entire section 15 for insights into streams. First fix the problem with invalid input. First you need to ensure that the user enters values that can be converted into integral values.
http://www.parashift.com/c++-faq-lite/input-output.html

Once you have solved that then you can probably figure out a way to test whether there is anything else in the stream and throw an error if so.
I was going to recommend in_avail() to detemine how many chars are left in the input buffer (any more than a newline should indicate more numbers/text):
http://www.cplusplus.com/reference/iostream/streambuf/in_avail/

However, cin.rdbuf()->in_avail() always returns 0 for me, no matter how many characters are really left in the input stream.
The in_avail() function is not required to return useful information.
Topic archived. No new replies allowed.