Convert String to Int with Stringstream

寵の児 提交于 2019-12-20 05:11:32

问题


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:


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



回答2:


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.



来源:https://stackoverflow.com/questions/6939260/convert-string-to-int-with-stringstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!