将整数转换为字符串 C++
我正在尝试将整数转换为字符数组,并且遇到了这段代码,
int i = 5;
std::string s;
std::stringstream out;
out << i;
s = out.str();
但是当我尝试打印 s
的值时,它仍然打印 5。我不知道它是否应该这样做或者我做错了什么?此外,我更希望能够将相同的 int 转换为 char 数组。但我将不胜感激在此事上的任何帮助。 谢谢! 代码取自: 用于将整数转换为字符串的 itoa() 的替代方案C++?
I am trying to convert an integer to char array and I came across this piece of code
int i = 5;
std::string s;
std::stringstream out;
out << i;
s = out.str();
But when I try to print the value of s
it still prints 5. I don't know if its supposed to do that or am I doing something wrong? Besides I would prefer if I could convert the same int to char array. But I would appreciate any help in the matter.
Thanks!
Code taken from: Alternative to itoa() for converting integer to string C++?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,它应该这样做。如果您对结果进行其他一些字符串类型操作(例如,将其与其他字符串连接、搜索字符串中的字符),您(主要)会注意到与直接打印数字的区别。
仅举个例子:
Yes, it's supposed to do that. You'd (primarily) notice the difference from just printing a number out directly if you do some other string-type manipulation on the result (e.g., concatenating it with other strings, searching for characters in the string).
Just for example:
如果您不想再担心此类问题,您可能会对
boost/lexical_cast.hpp
。If you would like to stop worrying about issues like that you might be interested in
boost/lexical_cast.hpp
.