1

have a little problem here:

int IntegerTransformer::transformFrom(std::string string){
    stream->clear();
    std::cout<<string<<std::endl;;
    (*stream)<<string;
    int i;
    (*stream)>>i;
    std::cout<<i<<std::endl;
    return i;
}

I by calling this function with the string "67" (other values dont work too) i get this output:

67
6767
1
  • Might want to simplify your stream references; use something like istream &theStream = *stream;, and you can then use the stream without dereff'n it every time Commented Aug 4, 2011 at 10:03

2 Answers 2

2

Did you notice there are two std::cout in the function itself?

Beside that also add this:

stream->str(""); //This ensures that the stream is empty before you use it.
(*stream)<<string;

By the way, why don't you use boost::lexical_cast?

int IntegerTransformer::transformFrom(std::string s){
     return boost::lexical_cast<int>(s);
}
Sign up to request clarification or add additional context in comments.

1 Comment

ty very much, seems that i missunderstood usage of stream->clear(); replaced it with stream->str(""); works fien now :)
0

stream->clear();

This does not "empty out" the stringstream's contents. It resets the error flags that get set when reading from the stream fails (e.g. because the text is not in the right format to read an integer).

The simplest way to deal with this is to just create a new, locally scoped stringstream:

int IntegerTransformer::transformFrom(std::string string){
    std::stringstream parser(string);
    int i;
    parser>>i;
    return i;
}

Notice how you also no longer have to mess around with pointers (and, I'm assuming, dynamic allocation), and that you can just use the constructor to set the initial value.

Having streams as data members of a class is a bad idea in general. They really aren't meant for that kind of use.

The next easiest solution is to use the member function that's actually intended for the job, .str(), as shown by Nawaz.

As also mentioned by Nawaz, scrapping the whole thing and just using boost::lexical_cast is probably a better idea anyway. Don't reinvent the wheel.

2 Comments

Wouldnt locally scoped streams allocate buffers each time the function is called? Im afraid of a unnecassary performance impact.
They will. If you really cared about performance, you wouldn't be putting yourself in the position of having to convert strings to ints in the first place. Unless you had to because e.g. the strings come from user input; but in that case, it will take the program much, much longer to actually read the string than to do this manipulation, and that delay is unavoidable, so...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.