void command()
	int CourseDistance, StartTime, FinishTime;
	char cmdChar = ' ';
		cout << "Command? : ";
			switch (cmdChar)
			case 'd': 
			case 'D': 
				cout << "Enter New Course Distance (NM): ";
				cin >> CourseDistance;
			case 's':
			case 'S':
				cout << "Enter New Race Start Time (08:00-17:00): ";
				cin >> StartTime;
			case 'f':
			case 'F':
				cout << "Enter Finish Time (Max Start + 24h, 0-23:59): ";
				cin >> FinishTime;
				cout << "Unknown!\n";

	} while (cmdChar != 'q');

my question is why does my output go like
Command? : d
Enter New Course Distance (NM): 10
Command? : Unknown!
Command? :

after I input a 10, a new command prompt comes up but automatically puts an "Unknown!" there and then asks for an input again. why does it do that? How can I not let the Unknown happen?

thank you!

5 Years
Discussion Span
Last Post by kuramahiei

When reading character-by-character you have to be aware of the newline in the buffer. Consider the following:

#include <iostream>

int main () {
    char c = 0;
    while (std::cin.get(c)) {
        if (c == '\n')
            std::cout << "<NEWLINE>" << std::endl;
            std::cout << c << std::endl;
    return 0;

and the output of running that program:


said another way. >> ignores the terminating new line char left in the input buffer (if any) by any previous input method, but get() does not, and it leaves the termniating newline char in the input buffer when removing input from the input buffer.

So, upon hitting the d key followed by the enter key the d key is removed from the input buffer and put into c but the newline char is still in the input buffer. You enter the switch statement and hit the 1, 0 and enter keys in that order. >> ignores the leading newline char, puts the 1 and 0 into CourseDistance and leaves it's terminating newline char in the input buffer. Since cmdChar is d you go through the loop again. before you can hit another key however, the program has already called get() again and it sees the newline char in the input buffer left by >>. It therefore puts the newline char in cmdChar which then defaults to Unknown and asks for another input.

A similar problem happens when mixing >> and getline() in the same program, so be careful as L7sqr said. Either don't mix input methods in the same program, or be aware of the different input method behaviors, or be sure the input buffer is always empty before you use the next type of input method. To empty the input buffer call the stream ignore() method with a suitably sized number of input char to ignore and a suitable termination char.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.