如何使用 C++ 字符串流来附加 int?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2066184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use C++ String Streams to append int?
提问by Goles
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)?
谁能告诉我或给我一个简单的例子,说明如何将 int 附加到包含单词“Something”(或任何单词)的字符串流中?
回答by Daniel A. White
stringstream ss;
ss << "Something" << 42;
For future reference, check this out.
为了将来参考,请查看此内容。
回答by Jerry Coffin
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).
对于普通流,要添加到最后,您可以使用std::ios::ate
或std::ios::app
作为第二个参数打开,但是对于字符串流,这似乎不能可靠地工作(至少对于真正的编译器——gcc 和 VC++ 都不产生输出)我希望何时/如果我这样做)。
回答by KeithB
If you are already using boost, it has lexical_castthat 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.
如果您已经在使用 boost,它有lexical_cast可用于此目的。它基本上是上述内容的打包版本,适用于可以写入流和从流中读取的任何类型。
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
如果您还没有使用 boost,它可能不值得使用,但如果您使用它,它可以使您的代码更清晰,尤其是做类似的事情
foo(string("something")+boost::lexical_cast<string>(12));