473,748 Members | 7,608 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Help With Switch Statements!

36 New Member
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.e of())
{



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



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


}
else
cout << sampleInput << endl;



}
cout << endl;


inFile.close();

return 0;
}

[code]
Oct 19 '08 #1
4 2045
archonmagnus
113 New Member
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 Recognized Expert Top Contributor
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
curiously enough
79 New Member
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 Recognized Expert Top Contributor
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
10908
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 switch-case has a variable (most probably an enumeration) & associated symbols or integral value. Selection is made, base on what symbol/value the variable holds. So
10
9584
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 'case' code snippet does not. (the code's function is illustrative.) ////////////////////////////////////////// //////// working 'if/else' switch //////// //////////////////////////////////////////
11
2208
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 > x: dosomestuff()
15
1547
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 the page by the 3rd level), and I find myself doing things like this to help me keep it straight: class MyClass { public void SomeMethod()
10
12323
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 program to demonstrate how a switch without breaks behaves vs. how I expected it to behave. The code includes: (1) a switch statement with breaks (2) the if/else statements that have the same results as (1) (3) a switch statement without breaks...
13
4531
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 known at run time. Therefore a lot of template based trick isn't too useful. Considering datafile float x(3) 3.5, 2.5, 8.9 double y(3) 2.7, -2.3, 1.2 int z(3) 5, 2, 3
5
1770
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 alert comes up. Why? I checked the following watch expressions at the blah blah point. id = 5843 reportType = "MANDATE"
11
4966
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 statements in switch #2 enter a 3rd switch. I don't receive any compile errors except whenever I attempt to add default switches to switches 2 or 3.
13
11830
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 just curious to find out is it effective to use this method?? or is there is any other alternative method present so that execution time and code size can be reduced?? Thanks in advance.
2
10040
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 is used to access and read the value stored in it C.A variable is allocated or deallocated in memory during runtime D.A variable can be initialized at the time of its creation or later 2. The.……types feature facilitates the definition of classes...
0
9367
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9319
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9243
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8241
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6073
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4599
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4869
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3309
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2213
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.