int number;
char letter;

cout << "\nEnter a number\n";
cin >> number;

cout << "\nEnter a letter\n";
cin >> letter;
cout << "\nThanks!";

Let's say I had 5 of these questions lined up, it seems the user could just type something like "1 a 2 3 4" on the first question and fill them all out at once. Likewise, how do I stop the user from simply entering 'b' for the first question and skipping the number all-together?

Recommended Answers

All 6 Replies

use a loop and validate user input

while(true)
{
   cout << "Enter a number\n";
   cin >> number;
   if( !cin.good() )
   {
        cin.clear();
        cin.ignore(1000,'\n');
        cout << "Error\n";
   }
   else
       break;
}

Well it works, but I don't really understand it.
How would I change it to only accept letters, or strings or whatever?

Its called data validation. After input the program needs to check the variable's contents for correct characters. If incorrect characters are detected then display error.

http://www.daniweb.com/tutorials/tutorial71858.html

I ran through the tutorial and it simply shows getting numerical input for strings. My problem is my program crashed any time a letter is input for a cin >> int variable.

Ancient Dragon's code works, but I don't understand the code well enough to manipulate it into my program.

My generic answer is to always read user input as a string. Where you are expecting a number, attempt to convert it. If the conversion is successful, great; otherwise, handle it however you choose.

The string conversion stuff may not be obvious right off the bat. My I'd recommend getting familiar with it rather than avoiding it.

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.