andyInCambridge
andyInCambridge

Reputation: 1225

After writing to a stringstream, why does extracting into a string cause that string to become bogus?

I'm encountering a puzzling bug involving stringstream. I've got a object whose properties I want to dump to a file using dumpState(). This object has a number of member objects, each of which has had operator<< defined for them. Here's the code:

void dumpState(int step){
  stringstream s;
  s << DUMP_PATH << step;
  string filename;
  //s >> filename;

  fstream f;
  f.open("fuuuuu.csv", fstream::out); 
  //f.open(filename.c_str(), fstream::out);  

  f << numNodes << '\n';
  f << nodes << '\n';
  f << numEdges << '\n';
  f << edges << '\n';
  f.close();
}

My intention is of course to write to a file whose name is determined by step. Unfortunately, I find that the values outputted are bogus. Tracking the bug down, I found that if I comment out "s>>filename;" the values are correct.

There must be some sort of flushing problem going on, but I don't know how to fix it. Any ideas on this rather evil looking bug?

UPDATE:

I think the problem was a rather complicated error due to a mistake elsewhere in my code. After restructuring my code, the original code I posted works fine.

Upvotes: 3

Views: 692

Answers (3)

Ben Voigt
Ben Voigt

Reputation: 283733

Among other possible problems, s >> filename; will only read up to the first whitespace.

Foo Bah has the correct solution.

Upvotes: 0

Robᵩ
Robᵩ

Reputation: 168716

I can't reproduce your problem using g++ 4.5.2 x86_64, so I can't confirm that this is the problem, but try this:

std::stringstream s;
s << DUMP_PATH << step;
s.flush();
std::string filename;
s >> filename;

Upvotes: 0

Foo Bah
Foo Bah

Reputation: 26271

you should use an ostringstream and call s.str() to get the contents.

Upvotes: 2

Related Questions