user1038665
user1038665

Reputation: 129

How can I check whether a user enters the same number twice? C++ Help?

I just need quick help. Here's a breakdown of some code:

char userLetter;
int userNumber;

cout << "Please enter a letter: ";
cin >> userLetter;

while(userLetter == 'A')
{
     cout << "Please enter a number: ";
     cin >> userNumber;

     //do something in the loop here

     cout << "Please enter a letter: ";
     cin >> userLetter;
}

Now I basically need to add something that will tell the user his entry is invalid if he enters the same number more than once. For example, let's say the user enters the letter A and the number 2. The while loop executes whatever it needs to do and then asks the user for a letter again. Let's say the user enters 'A' again. The loop then asks the user for another number, if the number is 2 again, the program should tell the user it's an invalid entry.

Any help?

Upvotes: 0

Views: 1848

Answers (5)

triclosan
triclosan

Reputation: 5714

std::map<char, int> m;
std::map<char,int>::iterator it;

it=m.find(userLetter);
if(it!=m.end() && *it==userNumber)
{ 
    std::cout << "it's an invalid entry" << std::endl;
    continue;
}

Upvotes: 0

R&#233;mi
R&#233;mi

Reputation: 3745

You should use a container (std::set, probably) to store numbers. You can insert with method "insert", and test if a number is in the set with method "find".

http://www.cplusplus.com/reference/stl/set/

Upvotes: 0

You could use a std::set of std::pair-s, or some std::map to keep the association between the letter and the number.

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258568

You can use a std::set to remember all entered numbers and see if each subsequent number is already in the set.

std::set<int> numbers;
while(userLetter == 'A')
{
     cout << "Please enter a number: ";
     cin >> userNumber;

     if ( numbers.find(userNumber) != numbers.begin() )
     {
          //prompt error here
          continue;
     }
     else
     {
          numbers.insert(userNumber);
     }

     //do something in the loop here

     cout << "Please enter a letter: ";
     cin >> userLetter;
}

Upvotes: 2

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361352

Store the previous number(s) in a std::vector and test for equality after reading the subsequent number(s) with the previously read and stored numbers.

Upvotes: 0

Related Questions