90 likes | 272 Views
C++ Language Tutorial. Lesson 4 – Input and selection. Getting Input Selection - Switch Selection - if. Getting input. We can get input from the user from the same library that we use for output • < iostream > • From that library we use ‘ cin ’
E N D
C++ Language Tutorial Lesson 4 – Input and selection • Getting Input • Selection - Switch • Selection - if
Getting input We can get input from the user from the same library that we use for output • <iostream> • From that library we use ‘cin’ • ‘cin’ for input, ‘cout’ for output
Example • Include the library (you should be doing this anyway by now) – #include <iostream> • • Declare a variable – IntaNum; • • Use cin to put input into that variable – cin >> aNum; • cin will continue to read until return is pressed
Data Types • Most basic data types can be read in • But beware, the wrong data in can cause a crash • The most generic data type is string • You can read numbers and text into a string • But, you then have to get the numeric data out • There are tools for this, we will not worry about them now S
Selection You often need to make decisions in a program There are two ways to do this: • if / else • switch case • ‘if’ can use any logical statement to make a choice • ‘switch’ takes the value of a single variable
Example (if) if(true) { // If some condition is true do something } else if(true) { // If some other condition is true do // something else } else // Otherwise do this
Example (switch) intaNum = 1; switch(aNum) { case 0: // Do something break; case 1: // Do another thing break; case 2: // Do something else break; default: // Do this if all else fails }
The end That concludes are last lesson you should now understand how to get input from the user And also make use of selection such as if or a switch. As allways the source code for the demonstration with fully explained comments (more extensive than the video), along with the execution able file is available on the site for download.