如何使用 C++字符串流附加 int?

发布于 2024-08-18 09:24:31 字数 65 浏览 12 评论 0原文

谁能告诉我或给我一个简单的例子,说明如何将 int 附加到包含单词“Something”(或任何单词)的字符串流中?

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)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

海的爱人是光 2024-08-25 09:24:31
stringstream ss;
ss << "Something" << 42;

为了将来参考,请查看此内容。

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

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

For future reference, check this out.

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

野侃 2024-08-25 09:24:31

我可能会按照这个一般顺序做一些事情:

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

使用普通流,要添加到末尾,您可以使用 std::ios::atestd::ios: 打开:app 作为第二个参数,但对于字符串流,这似乎不能可靠地工作(至少对于真正的编译器来说——gcc 和 VC++ 都不会产生我期望的输出) 。

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).

忆离笙 2024-08-25 09:24:31

如果您已经在使用 boost,它具有 lexical_cast可以用于此目的。它基本上是上述版本的打包版本,适用于可以写入流和从流中读取的任何类型。

string s("something");

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

如果你还没有使用 boost,它可能不值得使用,但如果你使用了,它可以使你的代码更清晰,特别是做类似的事情

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

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));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文