do-while confusion

I have some trouble with the do-while statement. The program is supposed to be some kind of interactive shell, e.g. if you press 'h' you get help options, if you press 'q' you exit the program.

1
2
3
4
5
6
7
8
9
10
11
12
13
char cmd;
std::string prompt="] ";
do {
	std::cout << prompt;
	cmd=std::getchar();
	if (cmd == 'h') {
		std::cout << cmd << std::endl;
	} else if (cmd == 'q') {
		std::cout << "bye..." << std::endl;
	} else {
		std::cout << "unknown command" << std::endl;
	}
} while (cmd != 'q');

I expected the code to produce the following output:

1
2
3
4
5
6
7
] h
h
] foo
unknown command
] q
bye...
bash$

Instead it does this:

1
2
3
4
5
6
7
] h
h
] unknown command
] foo
unknown command
] unknown command
] 

The q-command, however, works.

The problem seems to be with std::getchar() getting evaluated a second time before I enter any command. But why? And why two times?
getchar only reads one character (including the enter-character, which is partly responsible for all the "unknown command"'s you see).

If you want to read a complete line, you should use getline for this. http://www.cplusplus.com/reference/string/getline/

Ciao, Imi.
Hey imi :),

I used std::getline(). So the problem is solved. However, I still don't get the problem with std::getchar() since it reads into char cmd. Even if it read more than one char cmd can't store more than one char. So how does the newline character get into cmd?
It reads the first character, does the action, then reads the leftover newline, fails, then reads you next char, and so on. The input that wasn't read (the newlines and such) don't disappear when you don't read them immediately; they wait until your next read.
Thanks, that explains it.
Topic archived. No new replies allowed.