0

i want to send data f char array from main function to a istream member of a class as following code:

class StreamClass {
    public:
        std::shared_ptr<std::istream> istream_ptr;
};
int main(){    
    StreamClass sc;    
    char charArray[] = "hello world";
    sc.istream_ptr = std::make_shared<std::istream>(nullptr);   
}

i read this link Get an istream from a char* . However i want to do it without coding anything manually , just using simple std functions. is it possible.

user5005768Himadree
  • 1,267
  • 3
  • 16
  • 49

1 Answers1

1

The shared pointer is a bit overhead for this question. You need to deference it. Then you need to convert your array into a pointer. You also might want to create an out stream instead of an in stream, from your question. :

#include "iostream"
#include "memory"

class StreamClass {
    public:
        std::shared_ptr<std::istream> istream_ptr;
        std::shared_ptr<std::ostream> ostream_ptr;
};
int main(){
    StreamClass sc;
    char charArray[] = "hello world";
    sc.istream_ptr = std::make_shared<std::istream>(nullptr);
    sc.ostream_ptr = std::make_shared<std::ostream>(nullptr);
    std::cout << &(charArray[0]) << std::endl;
    *sc.ostream_ptr << &(charArray[0]);
    *sc.istream_ptr >> &(charArray[0]);
}

Jan Hackenberg
  • 361
  • 1
  • 12
  • Thanks @Jan Hackenberg. i was checking StreamClass sc in debug mode after charArray. But it seems the data actually was not stored inside istream_ptr . – user5005768Himadree Apr 13 '20 at 06:53
  • @user5005768Himadree In my answers code, the data from `charArray` should be stored in ` ostream_ptr`, see operator `<>`. `>>` is not defined for `std::istream`, only for `std::ostream`. – Jan Hackenberg Apr 13 '20 at 10:18