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;
	cin>>myIntegerInput;
	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;
	cin>>input;
	cout<<"You entered : "<<input<<endl;

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

	cout<<"Here are some calculations: "<<endl;
	cout<<5*4+2*5<<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:

5*4+2*5

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*(4+2)*5
= 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?
26
What is the current year?
2009
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).

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)