0% found this document useful (0 votes)
44 views

Basic Input/Output

This document provides an overview of input and output streams in C++. It discusses the cout and cin streams for standard output and input, as well as formatted output and input using the insertion (<<) and extraction (>>) operators. It explains how cout can be used to print literals, variables, and multiple values in a single statement. It also covers using endl and \n to insert newlines. For cin, it discusses extracting different data types and using getline to read an entire line of input instead of a single word.

Uploaded by

Brandon Funa
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views

Basic Input/Output

This document provides an overview of input and output streams in C++. It discusses the cout and cin streams for standard output and input, as well as formatted output and input using the insertion (<<) and extraction (>>) operators. It explains how cout can be used to print literals, variables, and multiple values in a single statement. It also covers using endl and \n to insert newlines. For cin, it discusses extracting different data types and using getline to read an entire line of input instead of a single word.

Uploaded by

Brandon Funa
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 7

//Name: Brandon funa Course-year: BSEE 2 Rating: _______

//Activity#1: Basic Input/Output

//Objective: To let the computer take a data, compute, and display the result.

Things to Learn from this activity:


cout // void
cin ; (semi-colon)
<< \n \t
>> endl (End of the Line)
““ identifier variable
Header file main program
{} ()
getline() int string

Standard output (cout)


On most program environments, the standard output by default is the screen, and the C++ stream object
defined to access it is cout.

For formatted output operations, cout is used together with the insertion operator, which is written as
<< (i.e., two "less than" signs).

cout << "Output sentence"; // prints Output sentence on screen


cout << 120; // prints number 120 on screen
cout << x; // prints the value of x on screen

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 << "Hello"; // prints “Hello” to the monitor


cout << Hello; // prints the content of variable Hello

Multiple insertion operations (<<) may be chained in a single statement:

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:

I am 24 years old and my zipcode is 90064

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:

cout << "This is a sentence.";


cout << "This is another sentence.";

The output would be in a single line, without any line breaks in between. Something like:

This is a sentence.This is another sentence.

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:

cout << "First sentence.\n";


cout << "Second sentence.\nThird sentence.";

This produces the following output:

First sentence.
Second sentence.
Third sentence.

Alternatively, the endl manipulator can also be used to break lines. For example:

cout << "First sentence." << endl;


cout << "Second sentence." << endl;

This would print:

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.

Standard input (cin)


In most program environments, the standard input by default is the keyboard, and the C++ stream
object defined to access it is cin.
For formatted input operations, cin is used together with the extraction operator, which is written as >>
(i.e., two "greater than" signs). This operator is then followed by the variable where the extracted data
is stored. For example:

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;

This is equivalent to:


cin >> a;
cin >> 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.

cin and strings


The extraction operator can be used on cin to get strings of characters in the same way as with
fundamental data types:
string mystring;
cin >> mystring;
However, cin extraction always considers spaces (whitespaces, tabs, new-line...) as terminating the
value being extracted, and thus extracting a string means to always extract a single word, not a phrase
or an entire sentence.

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
//____________________________________

//Questions for Program#1:


//10points for each answer and 30points for the summary.
//1. What is displayed after executing the program#1?
Note: The display "Press any key to continue" is not part of the output but only a confirmation from the
compiler that the program has been successfully executed.
 No displayed
//2. During execution of the program, can the value of the variables or identifiers x and y be changed to
other value during runtime?
 It can have no changes of that variable
//Questions for Program#2:
//1. What is displayed after executing the program#2?
 The sum of x and y
//2. During execution of the program, can the value of the variables or identifiers x and y be changed to
other value during runtime?
 No because the program has already have a value of the variable
Note: Runtime = the state of the program where it is currently running or in the process of executing
some command.

//Questions for Program#3:


//1. What is displayed after executing the program#3?
 The formula of sum of x and y
//2. During execution of the program, can the value of the variables or identifiers x and y be changed to
other value during runtime?
 Yes because you can change it manually the x and y
Summarize Your Learning:
Through experimenting this basic activity I understand that you must input the correct
program and also you must familiarize the given symbols the Cin and cout must considered as
the main thing to do a program.

You might also like