Thread: Need help looping this switch statement

  1. #1
    Registered User
    Join Date
    Jan 2008
    Posts
    17

    Need help looping this switch statement

    OK, so I wrote the program the way Elysia suggested, and it works great. Now, after the number is converted, i want to ask the user if they want to convert another value. If they type 'y' or 'Y', it prompts them again. 'n' or 'N' ends the program. Any suggestions are welcome, thanks. Here is my code:

    Code:
    #include "stdafx.h"
    #include <iostream>
    #include <iomanip>
    #include <fstream>
    #include <string>
    using namespace std;
    
    int main()
    {
    	double num1, meters, feet, kilos, pounds, liters, gallons, kms, miles;
    	int option;
    
    		cout << "Please select the conversion type you want to perform:" << endl;
    		cout << "1. Convert feet to meters" << endl;
    		cout << "2. Convert meters to feet" << endl;
    		cout << "3. Convert lbs. to kilograms" << endl;
    		cout << "4. Convert kilograms to lbs." << endl;
    		cout << "5. Convert gallons to liters" << endl;
    		cout << "6. Convert liters to gallons" << endl;
    		cout << "7. Convert square miles to square kilometers" << endl;
    		cout << "8. Convert square kilometers to square miles" << endl << endl;
    		
    		cin >> option;
    
    		switch(option)
    		{
    			case 1:
    				cout << endl << "Enter the number of feet to convert to meters:" << endl;
    				cin >> num1;
    				meters = num1 * 0.3048;
    				cout << num1 << " feet is equal to " << meters << " meters." << endl;
    				break;
    			
    			case 2: 
    				cout << endl << "Enter the number of meters to convert to feet:" << endl;
    				cin >> num1;
    				feet = num1 * 3.2808399;
    				cout << num1 << " meters is equal to " << feet << " feet." << endl;
    				break;
    
    			case 3:
    				cout << endl << "Enter the number of pounds to convert to kilograms:" << endl;
    				cin >> num1;
    				kilos = num1 * 0.45359237;
    				cout << num1 << " lbs. is equal to " << kilos << " kilograms." << endl;
    				break;
    
    			case 4:
    				cout << endl << "Enter the number of kilograms to convert to pounds:" << endl;
    				cin >> num1;
    				pounds = num1 * 2.20462262;
    				cout << num1 << " kilograms is equal to " << pounds << " lbs." << endl;
    				break;
    
    			case 5:
    				cout << endl << "Enter the number of gallons to convert to liters:" << endl;
    				cin >> num1;
    				liters = num1 * 3.7854118;
    				cout << num1 << " gallons is equal to " << liters << " liters." << endl;
    				break;
    
    			case 6:
    				cout << endl << "Enter the number of liters to convert to gallons:" << endl;
    				cin >> num1;
    				gallons = num1 * 0.264172051;
    				cout << num1 << " liters is equal to " << gallons << " gallons." << endl;
    				break;
    
    			case 7:
    				cout << endl << "Enter the number of square miles to convert into square kilometers:" << endl;
    				cin >> num1;
    				kms = num1 * 2.58998811;
    				cout << num1 << " square miles is equal to " << kms << " square kilometers." << endl;
    				break;
    
    			case 8:
    				cout << endl << "Enter the number of square kilometers to convert into square miles:" << endl;
    				cin >> num1;
    				miles = num1 * 0.386102159;
    				cout << num1 << " square kilometers is equal to " << miles << " square miles." << endl;
    				break;
    
    			default:
    				break;
    		}
    			
     return 0;
    }

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Now, after the number is converted, i want to ask the user if they want to convert another value. If they type 'y' or 'Y', it prompts them again.
    One way is to use a controlled infinite loop. In the loop, you place the switch with your value conversion logic. At the end of the loop, you ask the user if they want to convert another value. If the input is not 'y' or 'Y', you break from the loop.

    Alternatively, you can use a do while loop with the same basic idea.

    One question to think about is: what happens if the user enters more than one character?

    Incidentally, you might want to make your indentation a little more consistent.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Jan 2008
    Posts
    17
    I guess this program is written assuming that the user can read, and 'y' or 'n' are the only options he/she has.

    In reference to my indentation, what is wrong with it? I've always been told that its a personal choice. My code is easy to read, it's just how I do it.

    Anyhow, thanks for the suggestion

  4. #4
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Quote Originally Posted by ravens199 View Post
    I guess this program is written assuming that the user can read, and 'y' or 'n' are the only options he/she has.
    It's not a question of reading. You've never reached for y and hit u or h or t or 6 instead? Or, for that matter hit uy?

    Quote Originally Posted by ravens199 View Post
    In reference to my indentation, what is wrong with it? I've always been told that its a personal choice. My code is easy to read, it's just how I do it.

    Anyhow, thanks for the suggestion
    I don't think anyone's complaining (much) about the width, just that you pick one and go with it:
    Code:
    	double num1, meters, feet, kilos, pounds, liters, gallons, kms, miles;
    	int option;
    
    		cout << "Please select the conversion type you want to perform:" << endl;
    		cout << "1. Convert feet to meters" << endl;
    All these lines are at the same level in your program, therefore they start in the same column ... except that, somehow, they don't. There's no reason for a double indent here.

  5. #5
    Registered User
    Join Date
    Jan 2008
    Posts
    17
    I would want my program to say something like "Invalid entry. Please choose y/n" if anything other than y or n was typed.

    As for my syntax, I can see how it should be the same, but I'm an IE(industrial engineer) major taking a C++ class as an elective, so it's not that important to me.

    So back to the original question, how would I handle adding a y/n option making sure to be aware of syntax errors on behalf of the user?

  6. #6
    verbose cat
    Join Date
    Jun 2003
    Posts
    209
    How about adding a "Quit" option to your menu and adding another branch to your switch. Then you can loop over the switch until a boolean value is true, and mark that value true when the user selects the Quit option.

    You could then task the default case in your switch with informing the user that their input was invalid.
    abachler: "A great programmer never stops optimizing a piece of code until it consists of nothing but preprocessor directives and comments "

  7. #7
    Registered User
    Join Date
    Jan 2008
    Posts
    17
    Which type of loop would be best?

  8. #8
    verbose cat
    Join Date
    Jun 2003
    Posts
    209
    I expect you want the loop to run at least one time, and we don't know how many times the user will want to do a conversion, so a do...while loop would probably be most fitting.
    abachler: "A great programmer never stops optimizing a piece of code until it consists of nothing but preprocessor directives and comments "

  9. #9
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    FYI: This is how you would write it much shorter with less copying and pasting:
    Code:
    #include "stdafx.h"
    #include <iostream>
    #include <iomanip>
    #include <fstream>
    #include <string>
    using namespace std;
    
    struct Conversions {
    	string from, to;
    	double multiplier;
    	Conversions(string from, string to, double multiplier) :
    		from(from), to(to), multiplier(multiplier) {}
    };
    static const Conversions convert[] = {
    	Conversions("feet", "metres", 0.3048),
    	Conversions("meters", "feet", 1.0/0.3048),
    	Conversions("lbs.", "kilograms", 0.45359237),
    	Conversions("kilograms", "lbs.", 1.0/0.45359237),
    	Conversions("gallons", "liters", 3.7854118),
    	Conversions("liters", "gallons", 1.0/3.7854118),
    	Conversions("square miles", "square kilometers", 2.58998811),
    	Conversions("square kilometers", "square miles", 1.0/2.58998811),
    };
    
    int main()
    {
    	cout << "Please select the conversion type you want to perform:" << endl;
    	for (int i=0; i<sizeof(convert)/sizeof(convert[0]); ++i)
    		cout << i+1 << ". Convert " << convert[i].from << " to " << convert[i].to << endl;
    
    	int option;
    	cin >> option;
    
    	int i = option-1;
    	if (i >= 0 && i < sizeof(convert)/sizeof(convert[0]))
    	{
    		cout << endl << "Enter the number of " << convert[i].from << " to convert to "
    			 << convert[i].to << ":" << endl;
    		double num;
    		cin >> num;
    		cout << num << " " << convert[i].from << " is equal to "
    			 << num * convert[i].multiplier << " " << convert[i].to << "." << endl;
    	}
    	return 0;
    }
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  10. #10
    Registered User
    Join Date
    Jan 2008
    Posts
    17
    The do-while worked like a champ, thanks everyone on both threads who helped!

  11. #11
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by iMalc View Post
    FYI: This is how you would write it much shorter with less copying and pasting:
    That code looks messier and is harder to read, but screw that, I love to do optimizations like that!
    Although I would probably not do in in a program such as this, though.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  12. #12
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    Could you explain the red part of this structure please? Thanks!
    Code:
    struct Conversions {
    	string from, to;
    	double multiplier;
    	Conversions(string from, string to, double multiplier) :
    		from(from), to(to), multiplier(multiplier) {} 
    };

  13. #13
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    It's a constructor, that initializes from to and multiplier. It's used to initialize the objects in the static array, which leads me to a question of my own: why static? This is C++ and not C, so that would make it extern by default (I think?).
    The code may seem a little complex, but all it does is store pre-defined values in an array and then dynamically accessing that array and performing the calculation.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  14. #14
    Registered User
    Join Date
    Jan 2008
    Posts
    17
    Ok, I'm back with a completed program, except one thing doesnt work. I've added option 9; the user can quit by choosing 9. That works fine, but everything else typed other than 1-9 ends the program. Normally that is fine, but I've included an error message saying "invalid character please choose again". But, if you typed a letter it just quits. How do I get the program to re-prompt the user for another selection? The red is the part in question:

    Code:
    int main()
    {
    	double num1, meters, feet, kilos, pounds, liters, gallons, kms, miles;
    	int option;
    
    	cout << "English/Metric Conversion Calculator v1.0" << endl;
    	cout << "-----------------------------------------" << endl;
    	cout << "1. Convert feet to meters" << endl;
    	cout << "2. Convert meters to feet" << endl;
    	cout << "3. Convert lbs. to kilograms" << endl;
    	cout << "4. Convert kilograms to lbs." << endl;
    	cout << "5. Convert gallons to liters" << endl;
    	cout << "6. Convert liters to gallons" << endl;
    	cout << "7. Convert square miles to square kilometers" << endl;
    	cout << "8. Convert square kilometers to square miles" << endl;
    	cout << "9. Quit" << endl << endl;
    	
    	do							// makes sure the loop is ran at least once
    	{	
    	cout << endl << "Please select the conversion type you want to perform:" << endl;
    	cin >> option;
    
    	switch(option)
    	{
    		case 1:
    		cout << endl << "Enter the number of feet to convert to meters: ";
    		cin >> num1;
    		meters = num1 * 0.3048;
    		cout << endl << num1 << " feet is equal to " << meters << " meters." << endl;
    		break;
    			
    		case 2: 
    		cout << endl << "Enter the number of meters to convert to feet: ";
    		cin >> num1;
    		feet = num1 * 3.2808399;
    		cout << endl << num1 << " meters is equal to " << feet << " feet." << endl;
    		break;
    
    		case 3:
    		cout << endl << "Enter the number of pounds to convert to kilograms: ";
    		cin >> num1;
    		kilos = num1 * 0.45359237;
    		cout << endl << num1 << " lbs. is equal to " << kilos << " kilograms." << endl;
    		break;
    
    		case 4:
    		cout << endl << "Enter the number of kilograms to convert to pounds: ";
    		cin >> num1;
    		pounds = num1 * 2.20462262;
    		cout << endl << num1 << " kilograms is equal to " << pounds << " lbs." << endl;
    		break;
    
    		case 5:
    		cout << endl << "Enter the number of gallons to convert to liters: ";
    		cin >> num1;
    		liters = num1 * 3.7854118;
    		cout << endl << num1 << " gallons is equal to " << liters << " liters." << endl;
    		break;
    
    		case 6:
    		cout << endl << "Enter the number of liters to convert to gallons: ";
    		cin >> num1;
    		gallons = num1 * 0.264172051;
    		cout << endl << num1 << " liters is equal to " << gallons << " gallons." << endl;
    		break;
    
    		case 7:
    		cout << endl << "Enter the number of square miles to convert into square kilometers: ";
    		cin >> num1;
    		kms = num1 * 2.58998811;
    		cout << endl << num1 << " square miles is equal to " << kms << " square kilometers." << endl;
    		break;
    
    		case 8:
    		cout << endl << "Enter the number of square kilometers to convert into square miles: ";
    		cin >> num1;
    		miles = num1 * 0.386102159;
    		cout << endl << num1 << " square kilometers is equal to " << miles << " square miles." << endl;
    		break;
    
    		case 9:					// ends conversion calculator
    			cout << "Thank you for using Conversion Calculator v1.0!" << endl;
    		break;
    
    		default:
    		cout << "That is an invalid option.  Please choose again." << endl;
    	}
    	}
    	while(option != 9);			// keep looping to ask user as long as '9' isn't chosen
    return 0;
    }
    P.S. I know my code isn't short and sweet, I'm not a programmer. Bear with me please ;-)

  15. #15
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Code:
    while(option != 9);
    Well, if you enter 10 then 10 is not equal to 9 so it wont loop.
    There are several ways to solve it. Here are a few:
    put option = 9; in the default case.
    return 0; from case 9 and make it an infinite loop.
    Use a quit bool flag and only set it to true from case 9.

    I realise the code I posted is harder to read. I didn't expect it would get used. It's just a glimpse of the kind of way you'll come to write things after another 10 years or so experience.

    The static isn't any use in this case, it's just a habbit.

    I also could have removed the need to add and subtract 1 by adding a dummy entry at the start of the array.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Mutli Switch statement help
    By elwad in forum C Programming
    Replies: 9
    Last Post: 05-09-2009, 03:19 AM
  2. Switch statement / default:
    By kcpilot in forum C Programming
    Replies: 4
    Last Post: 12-02-2008, 03:14 PM
  3. Switch statement problem
    By jalex39 in forum C Programming
    Replies: 6
    Last Post: 03-08-2008, 04:05 PM
  4. switch statement issues...(undeclared identifiers)
    By mero24 in forum C++ Programming
    Replies: 2
    Last Post: 02-19-2005, 08:05 PM
  5. Efficiency with the switch() statement...
    By Unregistered in forum C++ Programming
    Replies: 3
    Last Post: 10-14-2001, 02:47 PM