Search code examples
c++cinstdstringistream

How does cin read strings into an object of string class?


Reading some documentation online I found that istream class was part of C++ long before the string class was added. So the istream design recognizes basic C++ types such as double and int, but it is ignorant of the string type. Therefore, there are istream class methods for processing double and int and other basic types, but there are no istream class methods for processing string objects.

My question is if there are no istream class methods for processing string objects, why this program works and how ?

#include <iostream>

int main(void)
{
  std::string str;
  
  std::cin >> str;
  std::cout << str << std::endl;

  return 0;
}

Solution

  • This is possible with the use operator overloading. As shown in the below example, you can create your own class and overload operator>> and operator<<.

    #include <iostream>
    
    class Number 
    {  
        //overload operator<< so that we can use std::cout<<  
        friend std::ostream& operator<<(std::ostream &os, const Number& num);
        
        //overload operator>> so that we can use std::cin>>
        friend std::istream &operator>>(std::istream &is, Number &obj);
    
        int m_value = 0;
        
        public:
            Number(int value = 0);    
    };
    
    Number::Number(int value): m_value(value)
    { 
    }
    
    std::ostream& operator<<(std::ostream &os, const Number& num)
    {
        os << num.m_value;
        return os;
    }
    
    std::istream &operator>>(std::istream &is, Number &obj)
    {
        is >> obj.m_value;
        if (is)        // check that the inputs succeeded
        {
            ;//do something
        }
        else
        {
            obj = Number(); // input failed: give the object the default state
        
        }
        return is;
    }
    
    int main()
    {
         Number a{ 10 };
         
         std::cout << a << std::endl; //this will print 10
         
         std::cin >> a; //this will take input from user 
        
        std::cout << a << std::endl; //this will print whatever number (m_value) the user entered above
    
        return 0;
    }
    

    By overloading operator>> and operator<<, this allows us to write std::cin >> a and std::cout << a in the above program.

    Similar to the Number class shown above, the std::string class also makes use of operator overloading. In particular, std::string overloads operator>> and operator<<, allowing us to write std::cin >> str and std::cout << str, as you did in your example.