Im trying to carry out input validation on a piece of code and have come across an issue.

Basically for the 1st input I used getline for the string and then for the 2nd input I use cin for the integer. I am aware you can convert the integer from a string with getline but I wish to use the validation underneath to cover for the fact that a user may enter a string instead of the required integer.

When this code runs the second revolution of the For Loop it fires out the first two requests without waiting for user input. I suspect its the clash with getline and cin but Im unsure how to resolve except for using getline which nullifies the validation code.

Any ideas?
If you need any more clarification on my long winded, tedious problem just ask.

Cheers.

int main ()
{
 	
	int n,x,numb;
	string mystr;
	
	for (n=0; n<N_TEAMS; n++)
	{
		cout << "Enter Seeded Team League : ";
		getline (cin,seeded[n].stdetails.league, '\n');
		cin.clear();

		cout << "Enter Seeded Team League Placing : ";
		cin >> seeded[n].stdetails.numb;

		cin.ignore(numeric_limits<int>::max(), '\n');



		if (!cin || cin.gcount() != 1)
		{
		cout << "Not a numeric value.";
		cin.ignore(numeric_limits<int>::max(), '\n');
		}
 
		else
		{
		cout << "Your entered number: " << seeded[n].stdetails.numb <<endl;
		cin.ignore(numeric_limits<int>::max(), '\n');
		}

		
	
		cout <<"\n";
		system("Pause");
		system("cls");
	

	}

	for (n=0; n<N_TEAMS; n++)
	{
	cout << "League is " << seeded[n].stdetails.league << endl;
	cout <<"\n";
	cout << "Numb is " << seeded[n].stdetails.numb << endl;
	system("Pause");
	cout <<"\n";
	}
}

You are screwing-up your gcount() by using ignore(). Get the count first, then ignore.

Hope this helps.

commented: Your da man! Safe +1

You are screwing-up your gcount() by using ignore(). Get the count first, then ignore.

Hope this helps.

Yep you are spot on, cheers.

I was close to figuring it as I had placed cin.clear(); after the ignore and it started to work, wasnt sure why though and youve cleared (no pun intended) that up.

Thanks again! 'Solved'

It would be just as easy, and permit multi-digit numbers, to input as a string and convert it...

#include <algorithm>
#include <cctype>
#include <functional>
#include <sstream>
#include <string>
using namespace std;
int main()
  {
  string s;
  int n;
  cout << "Please enter a number> ";
  getline( cin, s );
  if (find_if( s.begin(), s.end(), not1(ptr_fun<int,int>(isdigit)) ) != s.end())
    {
    cout << "That's not a number.\n";
    }
  else
    {
    stringstream( s ) >> n;
    cout << "You entered the number " << n << endl;
    }
  cout << "Have a nice day!\n";
  return EXIT_SUCCESS;
  }

Interesting Duoas, I'll give that a shot, thanks again!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.