How to use C++ String Streams to append int?

北战南征 提交于 2020-01-02 00:48:10

问题


could anyone tell me or point me to a simple example of how to append an int to a stringstream containing the word "Something" (or any word)?


回答1:


stringstream ss;
ss << "Something" << 42;

For future reference, check this out.

http://www.cplusplus.com/reference/iostream/stringstream/




回答2:


I'd probably do something on this general order:

#include <string>
#include <sstream>
#include <iostream>

int main() {      
    std::stringstream stream("Something ");

    stream.seekp(0, std::ios::end);
    stream << 12345;

    std::cout << stream.str();
    return 0;
}

With a normal stream, to add to the end, you'd open with std::ios::ate or std::ios::app as the second parameter, but with string streams, that doesn't seem to work dependably (at least with real compilers -- neither gcc nor VC++ produces the output I'd expect when/if I do so).




回答3:


If you are already using boost, it has lexical_cast that can be be used for this. It is basically a packaged version of the above, that works on any type that can be written to and read from a stream.

string s("something");

s += boost::lexical_cast<string>(12);

Its probably not worth using if you aren't using boost already, but if you are it can make your code clearer, especially doing something like

foo(string("something")+boost::lexical_cast<string>(12));


来源:https://stackoverflow.com/questions/2066184/how-to-use-c-string-streams-to-append-int

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