Beginning C++ programming. Understanding cin, cout and cerr.

C Programmers would remember the three streams stdin, stdout and stderr.
stdin is the default input stream of a program, stdout is the default output stream and stderr is the default error stream. All of these can be redirected. By default stdin is the keyboard, stdout and stderr are the vdu(screen). The C++ equivalent for these would be cin, cout and cerr. In addition, we also have a clog object.
Let us see their uses in a program that reads two integers and prints their sum.

#include <iostream>
using namespace std;
int main()
{
int x,y;
cerr<<"Enter 2 numbers \n";
cin>>x>>y;
cout<<x +y;
return 0;
}

Read the program carefully.
The program starts by printing a prompt.
Enter two numbers
This is printed via the statement.
cerr<<“Enter two numbers\n”;
Prompts and error messages should always be printed using cerr.
Two operators are being used.
>> is the input operator and << is the output operator. Both operators return the stream that is being used and therefore they can be cascaded.

Let us read a string and print it.

#include <iostream>
using namespace std;
int main()
{
char name[80];
cerr<<"Enter your name "<<"\n";
cin >> name;
cout<<name;
return 0;
}

The name we entered was Champak Roy, however only the first part of the name gets printed. Why?
By default cin uses white space as a delimiter and hence only the first part Champak was read. Let us try this next program.

#include <iostream>
using namespace std;
int main()
{
char fname[80],lname[80];
cerr<<"Enter your name "<<"\n";
cin >> fname>>lname;
cout<<fname<<lname;
return 0;
}

The cin object also provides a function named getline which allows the programmer to change this default behavior.
The getline function takes three parameters.
getline(char array, mas length, delimiter).

#include <iostream>
using namespace std;
int main()
{
char name[80];
cerr<<"Enter your name "<<"\n";
cin.getline(name,80,'\n');
cout<<name;
return 0;
}

The delimiter ‘\n’ is also the default value and therefore it can be dropped.

#include <iostream>
using namespace std;
int main()
{
char name[80];
cerr<<"Enter your name "<<"\n";
cin.getline(name,80);
cout<<name;
return 0;
}

Finally, we develop a program where we will read two names separated by a comma.

#include <iostream>
using namespace std;
int main()
{
char name1[80],name2[80];
cerr<<"Enter two names separated by a comma "<<"\n";
cin.getline(name1,80,',');
cin.getline(name2,80,'\n');
cout<<name1<<"\n"<<name2;
return 0;
}

Leave a Reply