top of page

Input and Output

 

Input output operations in C++  are performed using two i/o stream objects called cin and cout.

Stream is flow of data. An input stream is flow of characters into the program. And output stream is flow of characters out of the program. 

cout is an object of predefined output stream  and cin is an object of predefined input  stream. These are declared in  <iostream>

There are two more streams predefined in <iostream> header file - cerr and clog. cerr is standard error stream and clog is log stream. By default these two are associated with output stream - cout.

cout

 

cout (console out - cout) is an object of ostream class, and is used to display values on console. Values are printed using cout and << (insertion operator). 

 

Using cout is so much easier than printf. There is no need to remember format specifiers, no need to specify the type of output. Just name of variable is sufficient.



If you use the command
   cout<<"I heart C++";
the output
   I heart C++
is displayed on screen .



You can display multiple values by cascading << operator.

 

#include<iostream> 

using namespace std; 

int main()

      cout<<"Hello world"<<endl;

      int a = 10;int b = 2;

      cout<<a<<b<<endl;

 

Output is


Hello World
102


The program above prints Hello world and then prints a newline character followed by 102.

 

To use cout  in your program, you need to include header file iostream in your program and you need to  use either of the two lines.


using namespace std;
or  
using std::cout;

 

 because cout belongs to a namespace called std.

endl


endl is an io manipulator. It prints newline character and flushes the buffer.

Let us see with an example the need of this special character.

 

If we use
      cout<<"Hello";
  cout<<"this is next line";

 

the output will be


    Hellothis is next line

Because by default, cout does not print a new line character at the end of string.


So we should explicitly say cout<<endl or cout<<"\n" to display the content on next line.
 

cin

 

C++ uses cin object to read values from console.  cin uses >> (extraction operator) which can accept values of all different types.


cin>>m;

 

reads variable m from console.


cin>>a>>b;


reads two variables a and b.


Similar to cout, cin also needs the lines  #include<iostream> and using namespace std; in your program.

 

#include<iostream>

using namespace std;

int main()

{

     int a; float b;

      int c;

      cin>>a;

      cin>>b>>c;

      char str[10];

      cin>>str;

      cout<<a<<b<<c<<str<<endl;

}

 
If we run this program and give input as 8 8 9 hello world
output will be 889hello


 ./a.out
8
8 9
hello world
889hello


The reason for this is str is read only till a space.

Always remember that, similar to scanf in C, cin reads only till the white space when reading strings.

 

Input output errors


By default cin with strings reads only till first white space and next  extraction operator will read from the  buffer .  So if you type "Hello world", cin>>str will get only Hello, and the rest of string is in buffer.

To read the complete line of input, you can use cin.getline(char_array,size)
 
Extra characters in buffer can be flushed using cin.ignore(how_many,till_char);

Another problem with cin object is, when a wrong input is entered, an error flag is set which may cause an infinite loop.

 

while(m!=-1)

{

    cin>>m;

    cout<<m;

}

 
In the code above,  we are trying to read numbers till a -1 is entered. If user types a letter instead of a digit, execution goes into an infinite loop.

To avoid such errors, check for error using cin.fail(), then clear the error flag using cin.clear() and ignore the offending character.

 

while(m!=-1)

{

   cin>>m;

   if(cin.fail())

   {

      cin.clear();

      cin.ignore(256,'\n');

    }

   else

  {

     cout<<m;

   }

}

 

We are checking if cin has failed. If so, we are clearing the error flag and we are ignoring the offending input until next newline character or 256 characters.

You can also use while(cin>>m) so that when an error happens,  the loop terminates because extraction operator returns false on error.

 

while(cin>>m && m!=-1)

{

     cout<<m;

}

 
Simple and elegant !!

Exercises :

Write a program to read 5 numbers and print their sum of squares.

Write a program to read a name and then output "Interested in learning C++," followed by name.

Write a program to read a number and print its cube. If a string is entered instead of a number display an error message.


Namespaces      

 

C++ projects will be quite huge in size. In such a large project, possibly developed by different people, there is a high possibility of name conflict - two functions/classes/global variables having same name.

 

This might lead to a chaos. To avoid that C++ uses a concept called namespace. Functions, classes and global variables are enclosed in namespaces and identifiers need to be unique only within its own namespace. And each name is prefixed with its namespace.

All identifiers within a namespace are accessible to one another. But to use an identifier outside of the namespace, we need to prefix names  with namespace name and  scope resolution operator (:: ) such as 


n1::foo()
 

Let us look at an example.

namespace n1
{
  void foo()
  {
      cout<<" in namespce n1"<<endl;
  }
  int g = 10;
}
namespace n2
{
  float g = 200;
  void foo()
  {
       cout<<"in namespace n2"<<endl;
    }
}
int main()
{
      cout<<"g is "<<n1::g<<endl;
      n1::foo();
      cout<<"g from n2 is "<<n2::g<<endl;
      n2::foo();
}


 
In the code above, we define two global variables with same name g - the code does not produce error. Because they are in different namespaces.

Also notice that the names of variables and functions are prefixed with name of namespace (n1 and n2) and :: - which is scope resolution operator.

If we want to avoid repeated usage of scope resolution operator, we can bring the namespace into our program, by using the keyword "using"

 
 

namespace n1
{
  void foo()
  {
      cout<<" in namespce n1"<<endl;
  }
  int g = 10;
}
namespace n2
{
  float g = 200;
  void foo()
  {
       cout<<"in namespace n2"<<endl;
    }
}
using namespace n1;
int main()
{
      cout<<"g is "<<g<<endl;
       foo();      
}

 



Now variable g and function foo() are taken from namespace n1 - because of "using ..." statement.

All standard library objects - cin, cout, endl etc. are defined in a namespace called std.
 
In the program below, we are trying to use cin and cout using their namespace and ::.

 

e.g.

int m;

std::cin>>m;

std::cout<<m;


Instead of prepending std:: each time, you can use using namespace std; directive which brings the entire namespace std into scope.


using namespace std;


Now std namespace is available in our program, and you can use cin, cout, endl, string etc. without any prefix.

The third method with namespaces is, you can use using declaration, such as using std::cin; ,using std::cout;  that brings specified identifier into scope.

#include<iostream>

using std::cin;

using std::cout;

int main()

{

   int a;

   float b;

   cout<<"Enter an integer";

   cin>>a;

   cout<<"You have entered "<<a<<std::endl;

}

 
In the above program we are bringing only cin and cout into scope. So if we try to use other std name such as endl without prefix, we get an error.

 

Strings

 


Strings are a string of characters - like "Hello world" :). In languages like C, strings are represented as an array of characters.

In C++, for strings, you can use a character array just like in C. C string library functions can be accessed by including header file <cstring>

The better option is to use string objects. C++ standard library provides a string class. Unlike character arrays, string objects do not need size to be specified. They can be concatenated using + operator, can be compared using ==,> or < operator.
e.g.

char str1[10];

cin>>str1;

string str2="Hello world";

cout<<str2;

str2 = str2+" and good bye world";

if(str2=="Hello world")

    cout<<"it has not changed??";

 
string class is declared in namespace std. So you should use using namespace std or using std::string.

string object can be read and written using cin and cout. And it can be converted to c-string using function string.c_str() function.

Exercises:

  1. Write a program to read a string and display "Hello" followed by the string.

  2. Write a program to read two strings and determine which one is longer.

  3. Write a program to read 5 strings, store them in an array and print all the strings which contain the word "is"


 

bottom of page