January 13, 2021

C++ Input and Output

IN this section, we would learn about C++ inputs and output. This is very important in writing interactive programs that accept input from user and sent output to user as well.

The two objects use to accomplish this are: cout and cin.

  1. Output Using cout
  2. Input Using cin
  3. Example – Calculate Sum

 

1. Output Using cout

You use cout to display formatted output to the standart output device such as the monitor screen. Cout is an instance of the ostream class. Therefore, you need to include <iostream>. You use cout along with the stream insertion operator <<. Let’s take a simple example.

#include <iostream>
using namespace std;

int main() {
	cout << "Welcome to C++!";
	return 0;
}

The above code uses cout to display the message ‘Welcome to C++!’ to the screen.

The <iostream> file contains defintion for the following objects

  • cin – standard input stream
  • cout – standard output stream
  • cerr – unbuffered error stream
  • clog – buffered error stream

 

2. Input Using cin

The cin object is an instance of the istream class and is used to read user input from standard input, for instance, the keyboard. You use it with the stream extraction operator >>. The code below prompts the user for his name. The it gets his name as input and displays a greeting using the name input.

#include <iostream>
using namespace std;

int main() {
	string name;
	cout << "Please enter your name: ";
	cin >> name;
	cout << "Good day, " + name;
	return 0;
}

The output is shown below:


C++ Input and Output

What happens is that when the compiler encounters the cin>> statement, I pauses for user input. So when user enters a value and hits Enter, then the value is assigned to the variable, name.

 

3. Example – Calculate Sum

We could also us cout and cin with numbers. Let’s illustrate this using a simple calculator program. The program would prompt the user for a first number. Then prompt for a second number. Finally, it would display the sum of the two numbers.

#include <iostream>
using namespace std;

int main() {
	int num1;
	int num2;
	cout << "Enter the first number: ";
	cin >> num1;
	cout << "Enter the second number: ";
	cin >> num2;
	cout << "The sum is " << num1 + num2;
	return 0;
}

Note that the extraction operation have been used twice in the same like. This is completely acceptable.

But you may wonder what happens if the user enters a character, say, ‘A’ instead of a number. Well, there would be an error. In subsequent lessons, we’ll see how to handle this.

 

Leave a Reply

Your email address will not be published. Required fields are marked *