I'm just playing around with C++ as a preperation for coming assignments and well, exams. And I'm a little stuck with the switch statements. I've done this simple switch just to test the functions:

#include <iostream>

using namespace std;

int main(void)
{
	char input;
	
	cout << "\nChoose function.\n1. Test 1. \n2. Test 2. \n3. Test 3 \n4. Exit" << endl;

	cin >> in;

	do
	{
	switch(in)
	{
	case '1':
		cout << "test 1" << endl;
		break;
	case '2':
		cout << "test 2" << endl;
		break;
	case '3':
		cout << "test 3" << endl;
		break;
	case '4':
		cout << "Exiting program now" << endl;
		break;
	default:
		cout << "Not possible!" << endl;
		break;
	} // end switch
	} // end do
	while(in != '4');

	system("PAUSE");
	return 0;
} // end main

Basicly, I've just done the same thing I would've done in a Java program... And this makes the program go all funky. When I compile and build I get the choices and all that, but when I choose 1, 2 or 3 the program just outputs "test x" in an ever ongoing loop. I have to manually stop it from running.

So what have I done wrong? Where is the code that says "Run this selected part until infinity"? Tried removing the do-while, but then it just output the case statement in like 2 seconds and exited. What I would like is to output the thing in the case and then return to the menu.

Recommended Answers

All 2 Replies

Your cin >> in; (request the user for input) is outside the do...while loop.
So you ask input once and then it's continuously 'executing' the switch case with the same 'in' value.

Lol. That was a lame error to do. :P But thank you for the clarification!

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.