Cin for validation purposes.

Right now I'm playing around with a lab for my c++ class and the teacher kind of threw me a bit of a curve ball. He wants me ensure that the user entered a letter that will conform to the following: Must be a character.

I've tried a few different ways, and my logic is as follows:

1
2
3
4
5
cout <<"\n\nPlease Enter the letter you would like to start with ";
char d;
while (cin >> d){
	cout << "Please enter a letter, a number just isn't going to cut it. > ";
	cin >> d;


To my understanding, the code above should; under normal circumstances, cin to char d, and if cin should trip an error and not be able to write to char d, force the while loop into action.

Where did I make an error here? Can someone show me not only the idea behind why this is an error, but why exactly it would trip an error? I'm thinking it has something to do with the condition state of cin() in this case, but I'm just wanting to make sure.

Thanks!
Yes, but the problem is that once the error state is set, you won't be able to read anything anymore. You'll need to .clear() cin (to clear the error state) before you try to read anything else. You'll also need to clear the buffer somehow, otherwise you will read the same characters over and over again.
That's not really the issue I'm having though. Right now, any input (even a valid character) is tripping my error state....
example: (screenshot)- http://i.imgur.com/f1vcA.jpg
Hmm numblocke, my guess at looking your code is that you have only set d as a char (which denotes pretty much anything in respect to cin), that also lacks any initial value. This, along with the fact that the input buffer used by cin is not being cleared expressly, are the basic causes of the faulty behaviour. I think there may be some other options in the matter of input validation. Perhaps the getline command would be of use to you.
getline(cin, d);
I used the getline(cin, var) directive on another project a while back and needed to use cin.ignore to ensure that the data wasn't corrupted. I suppose I'll try to use a similar validation method here.
Anything the user types is a char. You need to explicitly validate it:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
cout << "\n\nPlease Enter the letter you would like to start with: ";
char c;
while (true)
  {
  // get the user's input
  string s;
  getline( cin, s );

  // validate it
  if (cin                    // input stream is still OK
  && (s.length() == 1)       // only a single character was entered
  && isalpha( c = s[ 0 ] ))  // that character is alphabetic only
    break;

  // validation failed: complain and reset
  cin.clear();
  cout << "Hey there, please enter a single alphabetic character only: ";
  }
cout << "Good job! You entered the letter '" << c << "'.\n";

Hope this helps.
Topic archived. No new replies allowed.