We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,752 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Help with limiting input C++

vector<string> guess(4);
		
	

		cout << "Input a Guess(e.g red blue green yellow): ";
		
        cin >> guess[0] >> guess[1] >> guess[2] >> guess[3];

this is part of my code to let the user input 4 different guesses, is there anyway I can limit the input by 4 so that if the user inputs more or less than 4 it would be invalid?
the input are basically strings

2
Contributors
3
Replies
8 Hours
Discussion Span
1 Year Ago
Last Updated
4
Views
ashboi
Newbie Poster
22 posts since Mar 2012
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

Why don't you use a counter and increment it when you get valid answers?
When it hits 4, drop out of the loop.

You could also just check to see if any of your variables is null (less than 4 condition).

If there are more than 4, could you ignore any additional input?

thines01
Postaholic
Team Colleague
2,433 posts since Oct 2009
Reputation Points: 447
Solved Threads: 408
Skill Endorsements: 7

sorry, as I'm still quite new to C++, could you provide an example?
thanks alot

ashboi
Newbie Poster
22 posts since Mar 2012
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

Something like this:

#include <iostream>
#include <istream>
#include <vector>
using namespace std;

bool isValid(string str)
{
   /*
      do some type of check to make sure str is valid
      ...like comparing it to a know color list
   */
   return true;
}

int main(void)
{
   vector<string> vecGuess;
   char strTemp[128] = {0};
   
   for(int i =0; i < 4; i++)
   {
      cout << "guess #" << (i+1);
      cin >> strTemp;

      if(!isValid(strTemp))
      {
         cout << "not valid" << endl;
         i--;
         continue;
      }

      vecGuess.push_back(strTemp);
   }

   return 0;
}

You will need to validate what the user enters in the isValid() function.

thines01
Postaholic
Team Colleague
2,433 posts since Oct 2009
Reputation Points: 447
Solved Threads: 408
Skill Endorsements: 7

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0596 seconds using 2.66MB