Search code examples
c++ifstreamstringstream

C++ Error using a custom ifstream class with a variable as argument


I am using a custom ifstream class

class plb_ifstream : public Parallel_istream {
public:
plb_ifstream();
explicit plb_ifstream(const char* filename,
                      std::istream::openmode mode = std::ostream::in );
~plb_ifstream();
virtual std::istream& getOriginalStream();

bool is_open();
void open(const char* filename, std::istream::openmode mode = std::ostream::in);
void close();
bool good();
private:
plb_ifstream(plb_ifstream const& rhs);
plb_ifstream& operator=(plb_ifstream const& rhs);
private:
DevNullBuffer devNullBuffer;
std::istream  devNullStream;
std::ifstream *original;

};

This works well with a single file like

plb_ifstream ifile("geometry.dat");

However when I try to use a variable in the argument (in a for-loop) like

for(plint num=1; num<4; num++)
{
    std::ostringstream ostr;
    ostr <<num<<".dat";
    std::string var = ostr.str();

    pcout <<"Reading geometry.."<<endl;
    plb_ifstream ifile(ostr.str());
    ifile >> boolMask;
    pcout<<"done..."<<endl;}

I get the following errors

error: no matching function for call to ‘plb::plb_ifstream::plb_ifstream(std::basic_ostringstream<char>::__string_type)’|
note: candidates are:|
note: plb::plb_ifstream::plb_ifstream(const plb::plb_ifstream&)|
note: no known conversion for argument 1 from ‘std::basic_ostringstream<char>::__string_type {aka std::basic_string<char>}’ to ‘const plb::plb_ifstream&’|
note: plb::plb_ifstream::plb_ifstream(const char*, std::ios_base::openmode)|
note:   no known conversion for argument 1 from ‘std::basic_ostringstream<char>::__string_type {aka std::basic_string<char>}’ to ‘const char*’|
note: plb::plb_ifstream::plb_ifstream()|
note:   candidate expects 0 arguments, 1 provided|

I did find some other solutions but they do not utilize ifstream. If there is a work around using only ifstream them I would appreciate the help


Solution

  • You probably need to replace:

    plb_ifstream ifile(ostr.str());
    

    with

    plb_ifstream ifile(ostr.str().c_str());
    

    to get C string equivalent