Basic Input/Output
Basic Input/Output
//Objective: To let the computer take a data, compute, and display the result.
For formatted output operations, cout is used together with the insertion operator, which is written as
<< (i.e., two "less than" signs).
The << operator inserts the data that follows it into the stream that precedes it. In the examples above,
it inserted the literal string “Output sentence”, the number 120, and the value of variable x into the
standard output stream cout. Notice that the sentence in the first statement is enclosed in double quotes
(") because it is a string literal, while in the last one, x is not. The double quoting is what makes the
difference; when the text is enclosed between them, the text is printed literally; when they are not, the
text is interpreted as the identifier of a variable, and its value is printed instead. For example, these two
sentences have very different results:
cout << "This " << " is a " << "single C++ statement";
This last statement would print the text “This is a single C++ statement”. Chaining insertions is
especially useful to mix literals and variables in a single statement:
cout << "I am " << age << " years old and my zipcode is " << zipcode;
Assuming the age variable contains the value 24 and the zipcode variable contains 90064, the
OUTPUT of the previous statement would be:
What cout does not do automatically is add line breaks at the end, unless instructed to do so. For
example, take the following two statements inserting into cout:
The output would be in a single line, without any line breaks in between. Something like:
To insert a line break, a new-line character shall be inserted at the exact position the line should be
broken. In C++, a new-line character can be specified as \n (i.e., a backslash character followed by a
lowercase n). For example:
First sentence.
Second sentence.
Third sentence.
Alternatively, the endl manipulator can also be used to break lines. For example:
First sentence.
Second sentence.
The endl manipulator produces a newline character, exactly as the insertion of '\n' does; but it also has
an additional behavior: the stream's buffer (if any) is flushed, which means that the output is requested
to be physically written to the device, if it wasn't already. This affects mainly fully buffered streams,
and cout is (generally) not a fully buffered stream. Still, it is generally a good idea to use endl only
when flushing the stream would be a feature and '\n' when it would not. Bear in mind that a flushing
operation incurs a certain overhead, and on some devices it may produce a delay.
int age;
cin >> age;
The first statement declares a variable of type int (integer) called age, and the second extracts from cin
a value to be stored in it. This operation makes the program wait for input from cin; generally, this
means that the program will wait for the user to enter some sequence with the keyboard. In this case,
note that the characters introduced using the keyboard are only transmitted to the program when the
ENTER (or RETURN) key is pressed. Once the statement with the extraction operation on cin is
reached, the program will wait for as long as needed until some input is introduced.
The extraction operation on cin uses the type of the variable after the >> operator to determine how it
interprets the characters read from the input; if it is an integer, the format expected is a series of digits
(whole numbers), if a string, a sequence of characters (common term: a word or more than one word).
NOTE: Do not enter more than one name for the program below.
PROGRAM EXAMPLE OUTPUT
1 // cin with strings
2 #include <iostream>
3 #include <string>
4 using namespace std;
5
6 int main ()
7 { What's your name? Homer
8 string mystr; Hello Homer.
9 cout << "What's your name? "; What is your favorite team? Isotopes
10 cin>> mystr; I like The Isotopes too!
11 cout << "Hello " << mystr << ".\n";
12 cout << "What is your favorite team? ";
13 cin>> mystr;
14 cout << "I like " << mystr << " too!\n";
15 return 0;
16 }
#include is used for specifying references (header file) for functions and commands to be used in the
program.
// is used to write comments (just a note and it is not read by the compiler when it is translated into
machine language.
{ represents the start of a function. In the program above, it is named as main, ended with its pair }.
using namespace std; is always used when a program includes string for its data and operations.
As you can see, extracting from cin seems to make the task of getting input from the standard input
pretty simple and straightforward. But this method also has a big drawback. What happens in the
example above if the user enters more than two names?
This is very poor program behaviour. Most programs are expected to behave in an expected manner no
matter what the user types, handling invalid values appropriately. Only very simple programs should
rely on values extracted directly from cin without further checking. A little later we will see how
stringstreams can be used to have better control over user input.
Extractions on cin can also be chained to request more than one datum in a single statement:
cin >> a >> b;
In both cases, the user is expected to introduce two values, one for variable a, and another for variable
b. Any kind of space is used to separate two consecutive input operations; this may either be a space, a
tab, or a new-line character.
To get an entire line from cin, there exists a function, called getline, that takes the stream (cin) as first
argument, and the string variable as second. For example:
NOTE: cin in a getline statement can take more than one word or name. It will take all data entered in
one line. The cin.get( ); clears up the keyboard's buffer.
PROGRAM EXAMPLE OUTPUT
1 // cin with strings
2 #include <iostream>
3 #include <string>
4 using namespace std;
5
6 int main ()
7 {
8 string mystr;
What's your name? Homer Simpson
9 //PRESS the ENTER key TWICE to PROCEED...
Hello Homer Simpson.
10 cout << "What's your name? ";
What is your favorite team? The Isotopes
11 getline (cin, mystr);
I like The Isotopes too!
12 cout << "Hello " << mystr << ".\n";
13 cin.get(); //clears up the keyboard's memory (buffer) in
14 preparation for the 2nd getline() statement below
15 cout << "What is your favorite team? ";
16 getline (cin, mystr);
17 cout << "I like " << mystr << " too!\n";
18 return 0;
19 }
Notice how in both calls to getline, we used the same string identifier (mystr). What the program does
in the second call is simply replace the previous content with the new one that is introduced.
The standard behavior that most users expect from a console program is that each time the program
queries the user for input, the user introduces the field, and then presses ENTER (or RETURN). That is
to say, input is generally expected to happen in terms of lines on console programs, and this can be
achieved by using getline to obtain input from the user. Therefore, unless you have a strong reason not
to, you should always use getline to get input in your console programs instead of extracting from cin.
Things to do:
1. Open the Visual Studio C++.
2. Open 3 separate C++ source file for each program listed below.
3. Encode (or copy from the part with a line to the next line and paste) the first program below and
execute it.
4. Encode the second program and execute it.
5. Encode the third program and execute it.
Program Listing:
//____________________________________
//Program#1:
//header files are like a book, used by the computer as a reference on how to use some command
#include<iostream.h> // iostream.h is the header file needed for cout and cin command
void main(void)
{ //start of the main program
//defining that x, y, and sum identifiers will only hold whole numbers (integers).
int x = 3, y = 5, sum = 0;
//compute the sum of x and y...
sum = x + y;
} //end of the main program
//____________________________________
//____________________________________
//Program#2:
#include<iostream.h>
void main(void)
{ //start of the main program
//defining that x, y, and sum identifiers will only hold whole numbers (integers).
int x = 3, y = 5, sum = 0;
//compute the sum of x and y...
sum = x + y;
//display the result to the monitor
cout<<"\n\n\n\t x = "<<x;
cout<<"\n\t y = "<<y;
cout<<"\n\t\t The sum of x and y is "<<sum<<"!!!";
} //end of the main program
//____________________________________
//____________________________________
//Program#3:
#include<iostream.h>
void main(void)
{ //start of the main program
//defining that x, y, and sum identifiers will only hold whole numbers (integers).
int x = 0, y = 0, sum = 0;
cout<<"\n Using the formula: sum = x + y: ";
cout<<"\n Enter a value for x: ";
cin>>x;
cout<<"\n Enter a value for y: ";
cin>>y;
//compute the sum of x and y...
sum = x + y;
//display the result to the monitor
cout<<"\n\n\n\t x = "<<x;
cout<<"\n\t y = "<<y;
cout<<"\n\t\t The sum of x and y is "<<sum<<"!!!";
} //end of the main program
//____________________________________