Advertisement

Trying to learn the switch statement

Started by February 02, 2002 05:12 PM
7 comments, last by justlnluck 22 years, 9 months ago
Hi everyone, I am an absolute beginner when it comes to programming. Right now, I am reading C++ How to Program 3rd edition on my spare time. I am doing every problem and exercise in the book and unfortunately there aren''t any answers in the back. I guess this is a good way though because it forces me to sit and think for a while until I figure out the problems. Anyway, right now I am stuck on exercise 49 in chapter 2. It is a problem dealing with the switch statement. I want a sentence to appear before the user enters a case. The problem is that the sentence reappears again before executing what is in the case. It seems like the while loop executes twice before the selected case starts executing. What am I doing wrong? Here is the source code...how do I post a screen of the source code from VC++ like most people do in this forum? Thank you for any advice, Justin // Exercise 249: Program that reads a series of pairs of numbers // (product number, quantity sold for the day) #include <iostream> using std::cout; using std::cin; using std::endl; int main() { int product; double t1 = 0, // All "t"''s are initialized to zero incase one or more t2 = 0, // "t"''s are not used during input. The "t"''s are summed t3 = 0, // after leaving the switch statement. t4 = 0, t5 = 0, total, // total amount of money from products quantity; // quantity of each product cout << "Hello, welcome to the program.\n" "Press to begin, to quit.\n"; while ((product = cin.get() ) != EOF ){ cout << "Enter Product Number: "; // I want this to line to only output each time // before the user inputs the product number. // Right now,it outputs twice: // Once before, once after. // The switch statement accepts a product number and then multiplise the value // of the product by the quantity. switch (product){ case ''1'': cout << "Enter Quantity Sold For Day: "; cin >> quantity; t1 = quantity * 2.98; break; case ''2'': cout << "Enter Quantity Sold For Day: "; cin >> quantity; t2 = quantity * 4.50; break; case ''3'': cout << "Enter Quantity Sold For Day: "; cin >> quantity; t3 = quantity * 9.98; break; case ''4'': cout << "Enter Quantity Sold For Day: "; cin >> quantity; t4 = quantity * 4.49; break; case ''5'': cout << "Enter Quantity Sold For Day: "; cin >> quantity; t5 = quantity * 6.87; break; case ''\n'': // ignore newlines case ''\t'': // ignore tabs case '' '': // ignore spaces in input break; default: // catch all other characters cout << "Incorrect product number.\n"; } } total = t1 + t2 + t3 + t4 + t5; //add up total value of products cout << "\n\nThe total value for your sales = $" << total << endl; return 0; }
This sucks. When I copied and pasted the source code, all the of the indentation disappeared.
Advertisement
quote: Original post by justlnluck
This sucks. When I copied and pasted the source code, all the of the indentation disappeared.

Read the FAQ; it talks about formatting.

Your statement appears in odd places because you''re not making sure cout actually sends the output to the screen. cout (and, indeed, all I/O streams) buffer their output until it reaches a certain size (so they don''t spend too much time writing), so if you want them to output immediately, you need to flush the buffer. In cout''s case you can do that either by inserting endl or flush.
cout << "This will appear immediately, but move us to the next line" << endl;cout << "This will appear immediately, but leave us on the same line" << flush; 

The difference between endl and flush is that endl inserts a newline (''\n'') and then actually inserts flush.

One last thing:
quote: Original post by justInluck
cout << "Hello, welcome to the program.\n"
"Press to begin, to quit.\n";

That''s a bug. You either need an insertion operator between the two strings, or another instance of cout on the second line. I assume you knew this and that it was just a typo.

Good luck!

[ GDNet Start Here | GDNet Search Tool | GDNet FAQ | MS RTFM [MSDN] | SGI STL Docs | Google! ]
Thanks to Kylotan for the idea!
as soon as you finish the switch, the while starts up again. You will have to put something after the switch that asks if the user wants to do more or is finished.
Also, press what to begin and what to quit? Put some more cases in the switch that allows the user to quit or anything else you want to do.
Lucas Henekswww.ionforge.com

  // Exercise 249: Program that reads a series of pairs of numbers //	                 (product number, quantity sold for the day)#include <iostream>using std::cout;using std::cin;using std::endl;using std::flush;int main(){	int product;		double t1 = 0,  // All "t"''s are initialized to zero incase one or more		   t2 = 0,  // "t"''s are not used during input. The "t"''s are summed 		   t3 = 0,  // after leaving the switch statement.		   t4 = 0, 		   t5 = 0,		   total,		// total amount of money from products		   quantity;	// quantity of each product		cout << "Hello, welcome to the program.\nPress [enter] to begin, [ctrl z] to quit.\n" << endl;		while ((product = cin.get() ) != EOF ){				 cout << "Enter Product Number: " << flush; 										   // I want this line to only output each time   										   // before the user inputs the product number. 										   // Right now,it outputs twice: 										   // Once before, once after.				// The switch statement accepts a product number and then multiplies the value 		// of the product by the quantity.				switch (product){			case ''1'':				cout << "Enter Quantity Sold For Day: ";				cin >> quantity;				t1 = quantity * 2.98;				break;			case ''2'':				cout << "Enter Quantity Sold For Day: ";				cin >> quantity;				t2 = quantity * 4.50;				break;			case ''3'':				cout << "Enter Quantity Sold For Day: ";				cin >> quantity;				t3 = quantity * 9.98;				break;			case ''4'':				cout << "Enter Quantity Sold For Day: ";				cin >> quantity;				t4 = quantity * 4.49;				break;			case ''5'':				cout << "Enter Quantity Sold For Day: ";				cin >> quantity;				t5 = quantity * 6.87;				break;			case ''\n'':	// ignore newlines			case ''\t'':	// ignore tabs			case '' '':	// ignore spaces in input				break;			default:	// catch all other characters				cout << "Incorrect product number.\n";						}	}		total = t1 + t2 + t3 + t4 + t5;	//add up total value of products		cout << "\n\nThe total value for your sales = $" << total << endl;	return 0;}[\source]  
I haven't done much C++ in the last year, but it seems to me...

When a product number is entered, two characters are typed: a digit and the return key . Your switch statement is ignoring the return key (and other whitespace), but your main loop is not. That's why your main loop seems to be executing twice; it actually is. Since you are doing this an exercise, I'll leave it up to you to figure out how to fix it.


Edited by - poozer on February 2, 2002 6:54:37 PM
Advertisement
he is right ur problem is the stream buffer.

i am not an iostream freak so this may not be the best way:


  if (cin.peek() == EOF) //test without remove break; //exit loopelse cin >> product; //get  
Thank you (ALL of you) for your tips and input. I played around with all of your ideas in different combinations, but had no luck. Unfortunately the book I am reading hasn''t introduced cin.peek() and no matter what I tried, the loop continued twice. I tried using if statements to stop it from reading the return (\n).

Well, I finally got the program running with the help of a C++ tutorial on the web. Reading the problem more carefully, I realized that the book didn''t expect me to have a statement appear between each number input. But I wanted one!! So I learned some commands off a tutorial and got it going.

I also learned today that for(;{} creates an infinite loop.
Beforehand, I had always used while(1==1){} and use an if statement like if(input = -1) break; to exit the loop. I also learned that while(1) does the same thing I guess. Thanks again all of you who gave me some tips. Here is the final code I made to get it working:

  // Exercise 249: Program that reads a series of pairs of numbers //	                 (product number, quantity sold for the day)// // Program finds total value of all products sold#include <iostream>enum BOOL { FALSE, TRUE };using std::cout;using std::cin;using std::endl;int main(){	int product;		double t1 = 0,  // All "t"''s are initialized to zero incase one or more		   t2 = 0,  // "t"''s are not used during input. The "t"''s are summed 		   t3 = 0,  // after leaving the switch statement.		   t4 = 0, 		   t5 = 0,		   total,		// total amount of money from products		   quantity;	// quantity of each product	BOOL exit = FALSE;				for(;;){		// a forever loop						cout << " **** Menu ****\n\n";        cout << "(1) Product 1 ($2.98).\n";        cout << "(2) Product 2 ($4.50).\n";        cout << "(3) Product 3 ($9.98).\n";        cout << "(4) Product 4 ($4.49).\n";        cout << "(5) Product 5 ($6.87).\n";		cout << "(6) Quit\n\n";        cout << "Product Number: ";        cin >> product;				// The switch statement accepts a product number and then multiplies the value // of the product by the quantity.				switch (product){			case (1):				cout << "Quantity Sold: ";				cin >> quantity;				t1 = quantity * 2.98;				break;			case (2):				cout << "Quantity Sold: ";				cin >> quantity;				t2 = quantity * 4.50;				break;			case (3):				cout << "Quantity Sold: ";				cin >> quantity;				t3 = quantity * 9.98;				break;			case (4):				cout << "Quantity Sold: ";				cin >> quantity;				t4 = quantity * 4.49;				break;			case (5):				cout << "Quantity Sold: ";				cin >> quantity;				t5 = quantity * 6.87;				break;			case (6):				exit = TRUE;				break; //end switch			case ''\n'':  // ignore newlines			case ''\t'':	// ignore tabs			case '' '':	// ignore spaces in input				break;			default:	// catch all other characters				cout << "Incorrect product number.\n";			}		if(exit)			break;	//end forever loop	}		total = t1 + t2 + t3 + t4 + t5;	//add up total value of products		cout << "\n\nThe total value for your sales = $" << total << endl;	return 0;}[\source]Output:  **** Menu ****(1) Product 1 ($2.98).(2) Product 2 ($4.50).(3) Product 3 ($9.98).(4) Product 4 ($4.49).(5) Product 5 ($6.87).(6) QuitProduct Number: 1Quantity Sold: 2 **** Menu ****(1) Product 1 ($2.98).(2) Product 2 ($4.50).(3) Product 3 ($9.98).(4) Product 4 ($4.49).(5) Product 5 ($6.87).(6) QuitProduct Number: 6The total value for your sales = $5.96Press any key to continue  
Oops, I meant while(1==1){if(input == -1) break;}

This topic is closed to new replies.

Advertisement