473,378 Members | 1,078 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

Help With Switch Statements!

Im working on a program in C++ and i need to use switch statements. this is my first using switches. how to put on in my while loop. can you give me an example.
heres what I have so far:

[code]

#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <cmath>



using namespace std;

int main()
{





string sampleInput;

ifstream inFile;
inFile.open("F:\\data3.txt");
ofstream outFile;
outFile.open("F:\\charges.txt");


while(!inFile.eof())
{



getline(inFile,sampleInput,'\n');



if ( sampleInput=="")
{
cout << endl;


}
else
cout << sampleInput << endl;



}
cout << endl;


inFile.close();

return 0;
}

[code]
Oct 19 '08 #1
4 2027
archonmagnus
113 100+
You need a switch variable. For example:

Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. int main (void)
  6. {
  7.     short method;
  8.     bool exiting = false;
  9.  
  10.     while (!exiting)
  11.     {
  12.         // Prompt the user for a method choice
  13.         cout<<"Select:"<<endl
  14.               <<"  1.) Method 1"<<endl
  15.               <<"  2.) Method 2"<<endl
  16.               <<"  3.) Method 3"<<endl
  17.               <<"  Anything else to exit"<<endl
  18.               <<"Selection: ";
  19.  
  20.         // Read the method of choice
  21.         cin>>method;
  22.  
  23.         // Use a switch statement for flow control
  24.         switch (method)
  25.         {
  26.             case 1:
  27.                 cout<<"Method 1"<<endl;
  28.                 break;
  29.  
  30.             case 2:
  31.                 cout<<"Method 2"<<endl;
  32.                 break;
  33.  
  34.             case 3:
  35.                 cout<<"Method 3"<<endl;
  36.                 break;
  37.  
  38.             // Anything else exits
  39.             default:
  40.                 exiting = true;
  41.                 break;
  42.         }
  43.     }
  44.  
  45.     return 0;
  46. }
  47.  
In the code example above, the code prompts the user for an input value. That input value is used in the switch statement to determine the program flow. In regard to the other portion of your question, the switch statement can be used in a while loop (or any other loop for that matter) in the same way as outside of a loop.
Oct 19 '08 #2
donbock
2,426 Expert 2GB
A switch statement selects from among a set of alternatives. The criteria used to make the selection is the switch variable. There's little point in using a switch statement if you don't have alternatives to choose between.

Were you given a problem to solve (with a hint that the switch statement would be helpful)?

Do you need to invent some problem that demonstrates the use of the switch statement?

Note: there are no programming situations where a switch statement is the only way to get the job done. You can do everything the switch does with an if -else if - else cascade. The main advantages of the switch statement are to people reading the code -- the structure makes it more apparent what is being attempted.
Oct 20 '08 #3
Switch statements are useless and long, and they can't be used with certain variable types. They never should have been invented in the first place. If statements are shorter, easier, and more efficient.
I personally have never found any use for this stupid statement.
Conclusion: Don't use switch statements unless asked to.
Oct 20 '08 #4
donbock
2,426 Expert 2GB
Switch statements are useless and long, and they can't be used with certain variable types. They never should have been invented in the first place. If statements are shorter, easier, and more efficient.
I personally have never found any use for this stupid statement.
Conclusion: Don't use switch statements unless asked to.
Despite opinions to the contrary, there are not as many cases with only One True Way to do the job as you might think. There are almost always trade-offs.

You write a program for two quite different audiences: the maintenance programmers (ie, anybody else who might read your code) and the machine. Let's look at some ways in which the switch statement can be helpful to each audience.

For maintenance programs (ie, people reading the code, including you) ...
... You only need to write the switch variable once; no risk of mistyping it anywhere in the if cascade.
... Logical 'OR' (where any of several values lead to the same choice) is much more concise in the switch statement than in an if cascade.
... The default clause can be used to trap impossible failures. The use of such traps is a hallmark of robust professional sottware. Static analysis tools like lint can warn you if you forgot to put in the default clause.
... When the switch variable is an enumerated type, static analysis tools like flexelint can warn you if you left any of the enumeration values out of the case clauses.
... When reading code casually, it is obvious that all case clauses depend on the single switch variable. If cascades must be examined more closely to determine that the same variable is tested every time.

For the machine ...
... I've heard rumors that some optimizing compilers turn switch statements into jump tables, although I've never run across one myself. A jump table would be a whole lot faster than an if cascade.
... Duff's Device!

Don't get me wrong, there are lots of situations where an if cascade is a better choice than switch. My code contains a lot more if statements than switch statements. I hope I've given you some reason to be a little less dismissive of the switch statement.
Oct 21 '08 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

10
by: Myster Ious | last post by:
Polymorphism replaces switch statements, making the code more compact/readable/maintainable/OO whatever, fine! What I understand, that needs to be done at the programming level, is this: a...
10
by: clueless_google | last post by:
hello. i've been beating my head against a wall over this for too long. setting the variables 'z' or 'y' to differing numbers, the following 'if/else' code snippet works fine; however, the ...
11
by: Scott C. Reynolds | last post by:
In VB6 you could do a SELECT CASE that would evaluate each case for truth and execute those statements, such as: SELECT CASE True case x > y: dosomestuff() case x = 5: dosomestuff() case y >...
15
by: Daniel Billingsley | last post by:
Speaking of trying to read deeply nested if-else blocks... I often find it's not always easy to tell one indent level from another (granted I keep my tab settings low so I'm not halfway across...
10
by: Evie | last post by:
I understand that when a switch statement is used without breaks, the code continues executing even after a matching case is found. Why, though, are subsequent cases not evaluated? I wrote a...
13
by: Fei Liu | last post by:
Hi Group, I've got a problem I couldn't find a good solution. I am working with scientific data files in netCDF format. One of the properties of netCDF data is that the actual type of data is only...
5
by: mark4asp | last post by:
Every time the function below is called I get the alert. So I put a deliberate error in there and I check the value of (reportType=='MANDATE') in Firebug, which is found to be true. But still the...
11
by: =?Utf-8?B?anAybXNmdA==?= | last post by:
Can switch statements be nested? I've got a large routine that runs off of a switch statement. If one of the switches in switch #1 is true, that enters switch statement #2. Some of the...
13
by: Satya | last post by:
Hi everyone, This is the first time iam posting excuse me if iam making any mistake. My question is iam using a switch case statement in which i have around 100 case statements to compare. so...
2
by: hcaptech | last post by:
This is my Test.can you help me ? 1.Which of the following statement about C# varialble is incorrect ? A.A variable is a computer memory location identified by a unique name B.A variable's name...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.