C++ Basic I/O
In this tutorial, you’ll learn how to take input from the user using the cin object and use cout object to display the result to the user.
C++ employs a useful abstraction known as streams to perform input and output operations on sequential media such as the screen, keyboard, or file. A stream is a container into which a programme can insert or extract characters. There is no need to know specifics about the stream’s media or any of its internal specifications. All we need to know is that streams are a source/destination for characters and that these characters are provided/accepted in a sequential order.
Below are some of the stream objects that is defined in the standard library (iostream)
stream | description |
---|---|
cin |
standard input stream |
cout |
standard output stream |
cerr |
standard error (output) stream |
clog |
standard logging (output) stream |
To use the iostream library’s capabilities, we must include the iostream header at the start of any code file that uses iostream’s content, as follows:
#include <iostream> // Rest# of your program
C++ Output using std::cout
In C++, cout stream object sends the formatted output to the console which is the standard output device. Here’s a sample program that demonstrates how to use std::cout object.
#include <iostream> int main() { std::cout << "Welcome to Developer Publish Academy"; return 0; }
Output
Welcome to Developer Publish Academy
How the Program works ?
- The iostream header file, which allows us to display output, is first included.
- Within the std namespace, the cout object is defined. The using namespace std; statement was used to use the std namespace.
- The main() function is the beginning of every C++ programme. The main() function is called first, and the code execution begins.
- cout is an object that prints the string ” ” enclosed in quotation marks. It is followed by the operator. return 0; represents the main() function’s “exit status.” This statement concludes the programme, but it is optional.
- cout uses the << which is called as the inserting operator. The operator inserts the data that comes after it to the stream that came before it.
We must use std::cout instead of cout if the using namespace std; statement is not included.
You can also use the cout to print the values of variables as shown below.
#include <iostream> int main() { int x { 10 }; std::cout << x; return 0; }
This program will print the output 10 on the screen.
You can chain multiple insertion operators in the same line as shown below.
#include <iostream> int main() { int x { 10 }; std::cout << x << " is a variable"; return 0; }
The above program will display “10 is a variable”.
Chaining insertions is especially useful when combining literals and variables in a single statement
cout does not add line breaks at the end by default, unless explicitly instructed to do so. Consider inserting the following two statements into cout:
cout << "This is 1st line"; cout << "This is 2nd line";
There would be no line breaks in the output, and it would be written on a single line.
This is 1st line This is 2nd line
To insert a line break, insert a new-line character at the exact position where the line should be broken. In C++, a new-line character is specified as \n.
cout << "This is 1st line\n"; cout << "This is 2nd line";
This produces the following output on the screen
This is 1st line
This is 2nd line
In addition, the endl manipulator can be used to break lines.
cout << "This is 1st line"<< endl; cout << "This is 2nd line";
This would print the following
This is 1st line
This is 2nd line
The endl manipulator inserts a newline character in the same way as the insertion of ‘n’ does, but it also flushes the stream’s buffer (if any), requesting that the output be physically sent to the device if it hasn’t already been done. This only affects fully buffered streams, and cout is (usually) not one of them. Still, it’s best to use endl just when flushing the stream is a benefit, and ‘n’ when it isn’t. Keep in mind that a flushing process has considerable overhead and may cause a delay on some devices.
It’s inefficient to use std::endl because it does two things: it changes the cursor to the next line and it “flushes” the output (makes sure that it shows up on the screen immediately). When using std::cout to write text to the console, std::cout frequently flushes output (and if it doesn’t, it usually doesn’t matter), thus flushing using std::endl is rarely necessary.
As a result, most people prefer to use the ‘n’ character instead. The ‘n’ character transfers the pointer to the next line without requesting a flush, therefore it will work better in situations where a flush would otherwise be impossible. Because it is both shorter and may be inserted, the ‘n’ character is also easier to read.
C++ – Taking Input from the user using cin
The keyboard is the default input in most programming environments, and the C++ stream object for accessing is cin.
#include <iostream> using namespace std; int main() { int number; cout << "Enter an Number "; cin >> number; cout << "The number you entered is " << number; return 0; }
Output
Enter an Number 86
The number you entered is 86
In the above program, we have used the C++ extraction operator >> together with the cin operator followed by the name of the variable (number) that should store the input data.
We must use std::cin instead of cin if the using namespace std; statement is not included.
The type of the variable after the >> operator determines how the extraction operation on cin interprets the characters read from the input; if it’s an integer, the format expected is a series of numbers, if it’s a string, a sequence of characters, and so on.
It’s possible to input more than one value on a single line, just as it’s possible to output more than one item of text on a single line.
|
This is same as
cin>> number1;
cin>>number2;
The user is supposed to enter two values, one for variable a and one for variable b, in both circumstances. Any form of space, such as a space, a tab, or a new-line character, is used to separate two successive input processes.
cin and restrictions with string
You can use the extraction operator on cin to get strings of characters in the same way that it can be used on fundamental data types.
For example
string string1;
cin>>string1;
The only catch here is that cin extraction considers spaces (whitespaces, tabs, new-lines, etc.) as terminating the value being extracted, extracting a string always means extracting a single word, not a phrase or an entire sentence.
There are couple of workarounds for this in C++.
You can use the getline() function that takes the stream as first parameter and the string variable as second parameter so it reads the complete line.
#include <iostream> #include <string> using namespace std; int main () { string mystr; cout << "What is your name? "; getline (cin, mystr); cout << "Hello " << mystr << ".\n"; return 0; }
String Stream
The standard header sstream> defines a type called stringstream, which allows a string to be treated as a stream, allowing extraction and insertion operations from/to strings to be performed in the same way that cin and cout are. This function is especially useful for converting strings to numerical values and vice versa.
string mystr ("1234");
int var1;
stringstream(mystr) >> var1
This declares a string with the value “1234” as its initial value, as well as an int variable. The third line then extracts from a stringstream created from the string using this variable. The numerical value 1234 is stored in the variable int in this piece of code.
Standard Error Stream (cerr)
The predefined object cerr is an instance of the ostream class. The cerr object is said to be attached to the standard error device, which is also a display screen, but the object cerr is un-buffered, and each stream insertion to cerr causes its output to appear immediately.
The cerr is also used in conjunction with the stream insertion operator, as shown in the following example.
#include <iostream> using namespace std; int main() { char str[] = "Error reading the file"; cerr << "Error message : " << str << endl; }
When the preceding code is compiled and executed, the following result is obtained:
Error message : Error reading the file
Standard Log Stream (clog)
The predefined object clog is a member of the ostream class. The clog object is said to be connected to the standard error device, which is also a display screen, but the clog object is buffered. This means that each insertion into clog may cause its output to be held in a buffer until it is filled or flushed.
As shown in the following example, the clog is also used in conjunction with the stream insertion operator.
#include <iostream> using namespace std; int main() { char str[] = "Error reading the data"; clog << "Error message is " << str << endl; }
When the preceding code is compiled and executed, the following result is obtained:
Error message is Error reading the data.
With these small examples, you wouldn’t be able to tell the difference between cout, cerr, and clog, but when writing and running large programmes, the difference becomes obvious. As a result, it is best practise to display error messages using the cerr stream and to display other log messages using the clog stream.