开发者

Convert String to Int with Stringstream

开发者 https://www.devze.com 2023-03-25 23:55 出处:网络
have a little problem here: int IntegerTransformer::transformFrom(std::string string){ stream->clear();

have a little problem here:

int IntegerTransformer::transformFrom(std::string string){
    stream->clear();
    std::cout开发者_JS百科<<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


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);
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号