Anshul Pareek
Anshul Pareek

Reputation: 17

making object of istream class, and taking input

#include<iostream>
using namespace std;
int main()
{
 istream A;
 int a;
 A>>a;
}

here i am making object of istream class, to take input. but the compiler shows error which I can't understand. Please help me with it...

#include<iostream>
using namespace std;
class Car
{
 private:
    string name;
    string model;
    int engine;
    public:
    friend istream& operator>>(istream&, Car&);     
    friend ostream& operator<<(ostream&, Car);      
};istream& operator>>(istream &d, Car &e) {
    d>>e.name>>e.model>>e.engine;              
    return d;
}ostream& operator<<(ostream &d, Car e)      
{
    d<<e.name<<" "<<e.model<<" "<<e.engine;
    return d;
}
int main()
{
    Car a;
    Car b;
    cout<<"enter car credentials";
    cin>>a>>b;                        
    cout<<a<<b;
}

i want to overload the extraction and insertion operators >> << by myself, in my class. so here I have to make references of istream and ostream. so I want to know why I can't make objects of them. I'll add the complete code.. –

Upvotes: 0

Views: 1465

Answers (2)

Yksisarvinen
Yksisarvinen

Reputation: 22219

std::istream is a bit of an abstraction (although it's not an abstract class). It wraps some underlying memory buffer and exposes convenient methods to extract data from that buffer.

What is important is that it needs a buffer from which it can extract data. You must provide such buffer to create std::istream object, and creating such buffer manually is rather difficult.
This is why no one uses std::istream directly, but rather we use std::cin for reading input from console, std::ifstream for reading from files and std::istringstream for reading from strings.

You could extract underlying buffer from std::cin to initialize another std::istream (see it online)

int main()
{
    std::istream is {std::cin.rdbuf()};
    int a;
    is >> a;
    std::cout << a;
}

It is probably possible to avoid using std::cin and initialize it directly from stdin (the object that represents resource provided by the operating system), but I have no idea how do that.

Upvotes: 3

Johann Gerell
Johann Gerell

Reputation: 25581

Use the std::cin instance:

#include<iostream>

int main()
{
    int a;
    std::cin >> a;
}

Reference here: https://en.cppreference.com/w/cpp/io/cin

Upvotes: 0

Related Questions