Basic Input and Output
Basic Input and Output
Medel
Valencia
MODULE
Computer Programming 1
CC112
I. Lesson Title:
Basic Input / Output
Texts:
1. Learn C++ Programming, Turtorialspoint, 2014, Chapter XXI: Basic Input/Ouput
Reference List:
1. Tutorialspoint. (2014). Learn C++ Programming Language. Hyderabad, Telangana,
India. Retrieved from www.tutorialspoint.com
#include <iostream>
using namespace std;
int main( )
{
char str[] = "Hello C++";
cout << "Value of str is : " << str << endl;
}
When the above code is compiled and executed, it produces the following result:
The C++ compiler also determines the data type of variable to be output and selects the
appropriate stream insertion operator to display the value. The << operator is overloaded to
output data items of built-in types integer, float, double, strings and pointer values
(Tutorialspoint, 2014).
The insertion operator << may be used more than once in a single statement as shown
above and endl is used to add a new-line at the end of the line.
{
char name[50];
cout << "Please enter your name: ";
cin >> name;
cout << "Your name is: " << name << endl;
}
When the above code is compiled and executed, it will prompt you to enter a name.
You enter a value and then hit enter to see the following result:
Please enter your name: cplusplus
Your name is: cplusplus
Tutorialspoint (2014) says that the C++ compiler also determines the data type of the
entered value and selects the appropriate stream extraction operator to extract the value and store
it in the given variables.
The stream extraction operator >> may be used more than once in a single statement. To
request more than one datum you can use the following:
cin >> name >> age;
This will be equivalent to the following two statements:
cin >> name;
cin >> age;
The Standard Error Stream (cerr)
Tutorialspoint (2014) stated that the predefined object cerr is an instance of 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[] = "Unable to read ... ";
cerr << "Error message : " << str << endl;
}
When the above code is compiled and executed, it produces the following result:
Error message : Unable to read....
You would not be able to see any difference in cout, cerr and clog with these small examples,
but while writing and executing big programs the difference becomes obvious. So it is good
practice to display error messages using cerr stream and while displaying other log messages
then clog should be used (Tutorialspoint, 2014).
GOOD JOB!