Search code examples
c++fstreamistringstream

how to convert ifstream to istringstream


I have a function that reads through an istringstream and does some operations on it so ... I am trying to read in a file using fstream and convert the fstream object to an istringstream in order to pass it to my function. I don't know how to do this. Any help would be much appreciated. I am still pretty much a beginner so please keep it simple if you can.

string inputFile(argv[1]);    
ifstream inFile(inputFile.c_str());    
istringstream is;

is >> inFile.rdbuf(); //*******This is wrong and is what I'm having trouble with

function(is);

Solution

  • What you want is std::istream_iterator:

    std::string myString ( std::istream_iterator(inputFile) , std::istream_iterator() ) ;
    std::istringstream is ( myString ) ;
    

    This creates a string with the contents of inputFile by using a begin iterator (std::istream_iterator(inputFile)) and an end iterator (std::istream_iterator()). It then creates an istringstream from that string.

    This solves your immediate problem, but there is almost certainly a better way to do what you are trying to do. For example:

    • Pass an istream instead of an istringstream (because then you don't have to copy it).

    • Change your algorithm to not need an istringstream.