ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Lesson 3 : More on Basic Input and Output in C++

Updated on November 24, 2009

3.1 Console Output

In previous lessons, we have already seen console output in C++ in action. In this section, we will explore it further, and practice a little more, before moving on to console input.

In C++, console output is provided for us as part of a library, called <iostream>. The iostream library is included at the top of a program that will make use of cout, the console output variable.

Code Sample 3.1-1

#include <iostream>
using namespace std;

int main()
	int myFavoriteInt = 150;
	double myFavoriteDouble = 543.2;
	char myFavoriteChar = 'b';

	cout<<"My favorite int = "<<myFavoriteInt<<endl;
	cout<<"My favorite double = "<<myFavoriteDouble<<endl;
	cout<<"My favorite character = "<<myFavoriteChar<<endl;

	return 0;

Figure 3.1-1

We can see the output of the code in Code Sample 3.1-1 in Figure 3.1-1.

Examine the code in Code Sample 3.1-1 carefully to ensure that you understand exactly what is going on.

At the top, we must include the <iostream> library, because this is where our console output variable, cout is defined.

Later in the program, we have our main() function. Inside of the main function is where all the magic takes place.

We declare three variables near the top of the main() function.

  • int myFavoriteInt
  • double myFavoriteDouble
  • char myFavoriteChar

These variables are assigned values: 150, 543.2, and 'b', respectively. And finally, after declaring these variables, we print them, prefixed with a string literal indicating what is about to be printed.

For example, in the case of myFavroiteInt, you will notice a string that says "My favorite int = ". Notice that it is inside double quotes, and that we did leave a space inside the double quotes, right after the equals sign. And, after the string literal, comes the stream insertion operator, <<, and then our variable, myFavoriteInt, then another stream insertion operator, <<, and finally, the endl variable followed by a semi-colon.

Recall that the variable endl creates a newline.

As a test, remove all the endl variables, recompile, and rerun your program.

Code Sample 3.1-2

#include <iostream>
using namespace std;

int main()
	int myFavoriteInt = 150;
	double myFavoriteDouble = 543.2;
	char myFavoriteChar = 'b';

	cout<<"My favorite int = "<<myFavoriteInt;
	cout<<"My favorite double = "<<myFavoriteDouble;
	cout<<"My favorite character = "<<myFavoriteChar;

	return 0;

Figure 3.1-2

Notice in Code Sample 3.1-2 that we have the exact same code as before, except we have removed all the endline variables.

This yields a very different output in Figure 3.1-2.  As you can see, it is quite messy.  The program will be executed and do exactly what it is told.

Since it was never told to move to the next line in between the different statements, it didn't.  This is why the endl variable is useful in providing clean and readable output.

3.2 Console Input

 So far, we have seen several programs that have printed strings, the contents of variables, and literal calculations out to the console.  But, one of the more impressive aspects of programs is that the user of the program can interact with the program.

The <iostream> library provides a variable to take care of the task of acquiring user input.  Since the variable cout stands for console ioutput, the variable used for input from the keyboard into the console is cin.

The cin variable acts in a similar fashion to cout, except this time, it uses the stream extraction operator >>, and sends the information collected into a variable.

For example, if we had asked the user to enter an integer that we want to store, the statement that does just that looks like this:

cin >> userInput;

This is of course assuming that userInput is an integer that was declared earlier in the program.

To get our feet a little more wet, let's examine a full program that utilizes both cout and cin.

Code Sample 3.2-1

#include <iostream>
using namespace std;

int main()
	int myIntegerInput = 0;

	cout<<"Please enter an integer: "<<endl;
	cout<<"The integer you entered was : "<<myIntegerInput<<endl;
	cout<<"Multiplied by two, this yields: "<<myIntegerInput * 2 <<endl;

	return 0;

Figure 3.2-1

 In Code Sample 3.2-1, we can see how cin is used.

First, we declared an integer named myIntegerInput, and initialized it to 0.  As a side note, initializing variables is typically done when they are declared.  This is because if you don't assign a value to them, they will contain a bunch of meaningless garbage data leftover in memory from whomever (or whatever) used that portion of memory last.

After we declare our variable to contain the input from the user, we prompt the user for input.

Figure 3.2-1 shows the entire transaction.  However, it is important to note that when the program initially executes, it prints out "Please enter an integer:" and then moves the insertion point to the next line and waits for the user to input a value and hit enter.

In the case of Figure 3.2-1, the user (me in this case) entered 123.  Because of the cin statement in the code, the value 123 is stored in myIntegerInput. 

So, when the next cout statement occurs, the variable myIntegerInput is echoed, that is, printed back, to the user. 

And finally, just to show some of the capabilities of C++, I had the program multiply the integer that the user input by 2, and print out the result.  Notice I did not have to create a separate variable to store the result of the multiplication, but rather just did the calculation inline in the cout statement.

3.3 Putting It All Together

In the previous sections, we saw how cout<< and cin>> were able to send output to the console, and receive input from the keyboard, respectively.

In this section, I offer a code sample that shows some of the interesting things that occur with input and output.  Additionally, this will also reveal some interesting things about how data types matter, and how calculations are performed.

Code Sample 3.3-1

#include <iostream>
using namespace std;

int main()
	int x = 50;
	double y = 50.0;
	double input = 0.0;
	int input2 = 0;

	cout<<"Please enter a number: "<<endl;
	cout<<"You entered : "<<input<<endl;

	cout<<"Please enter an integer: "<<endl;
	cout<<"You entered : "<<input2<<endl;

	cout<<"Here are some calculations: "<<endl;
	cout<<x * y<<endl;
	cout<<x / y<<endl;

	cout<<5 /2 <<endl;  //integers only
	cout<<5.0/2.0<<endl; //doubles

	return 0;

Figure 3.3-1

 Code Sample 3.3-1 shows a larger program than we have seen before.

In this sample, we have four variables that we are working with:

  • An integer, x = 50
  • A double, y = 50.0
  • A double, input = 0.0 initially.  It will later change its value based on user input
  • An integer, input2 = 0 initially.  It will also change its value based on user input

After the declaration and initialization (assignment) of the four variables, several outputs and inputs take place. 

In the first block of code, the user is prompted for a number, and the result is stored in input.  In the example in Figure 3.3-1, the user enters 47.3 and then the program echoes 47.3.

Notice, however, what happens in the next code block.  The variable input2 is an integer, not a double.  But the user enters 47.3 again, which is a double.

The .3 is truncated, or removed.  So, the integer variable input2, which can only store integers loses the .3 part of the user's input of 47.3.

Note that if the user enters a number, say, 47.8, the result stored in the integer variable will still be 47, not 48.  The number is not rounded to the nearest whole number.  The decimal portion of the number is simply removed.

As we continue through the program, some calculations are performed to show you how C++ makes calculations.

For the integer literals being computed:


we see that C++ follows the order of operations.  Thus, it performs the multiplications first, yielding 20+10, and then performs the addition, resulting in 30.

As an exercise, put parentheses around the 4+2.  Just like in mathematics, parentheses take priority over multiplication, so the result will be as follows:

= 5*6*5
= 150

The next operations performed are x * y, and then x / y.  Notice that even though one of the variables is an integer, and the other a double, we can perform mathematical operations on them. 

Finally, we see two interesting results near the bottom of the program.

5/2 yields 2.  Why?

Because 5 and 2 are integers, so the answer is 2.5, but the .5 is truncated from the answer.

In the next statement, 5.0/2.0, which appears to be the same problem, the answer is what we expect:  2.5.  This is because 5.0 and 2.0 are doubles, and therefore the information about the decimal values are not lost.


3.4 Summary and Conclusions

In this lesson, we explored more about how console input and output works.  We also learned more about how C++ performs calculations.

3.5 Exercises

 1.  Write a program that asks the user to enter the initials of their first and last names.  Print their initials, with each initial on its own line.

2.  Write a program to ask the user to enter their current age, and the current year.  After the current age and current year are retrieved, the program should tell the user what year they were born in.  A typical interaction may look like:

What is your current age?
What is the current year?
You were born in : 1983.

3.  Write a program that asks the user to input an integer, and print out the square of the number they entered.  For example, if the user enters, 3, it should print out 9  (since 3*3 is 9).


    0 of 8192 characters used
    Post Comment

    No comments yet.

    Click to Rate This Article