Jump to content
  • Advertisement
Sign in to follow this  
Boder

Read Line into stringstream.rdbuf()

This topic is 4500 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Why does the input fail when passing the string buffer of a string stream into the get() method for an ifstream?
#include <sstream>
#include <fstream>
#include <iostream>
#include <cassert>

using namespace std;

char const * const text =
"This text is const \n\nconst for you and const for me. \n\nDo you like const text? \n\nI do.\n";

int main()
{

 ofstream out("text.txt");
 out << text;
 out.close();

 ifstream in("text.txt");
 stringstream buffer;

 while( !in.eof() )
 {

  in.get( *buffer.rdbuf() );
  cout << buffer.str() << endl;
  assert( in.good() );

 }

 in.close();

}

Share this post


Link to post
Share on other sites
Advertisement
The std::istream.get() function does not consume the delimiter, so the next iteration through the loop it copies nothing from the input buffer to the output buffer. Not copying anything sets the input buffer into an error state.

The default delimiter is newline.

This is a pretty obscure function to use in application code. You may find there is a reason why you don't generally see it used.

Share this post


Link to post
Share on other sites
I kind of got it to work. Thanks for the tip.

while( !in.eof() && in.good() )
{
while( in.peek() == '\n' ) in.get();
in.get( *buffer.rdbuf() );
cout << buffer.str() << endl;
buffer.str("");
}

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!