将整数转换为字符串 C++

发布于 2024-10-30 17:15:17 字数 405 浏览 6 评论 0原文

我正在尝试将整数转换为字符数组,并且遇到了这段代码,

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 技术交流群。

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

发布评论

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

评论(3

静若繁花 2024-11-06 17:15:17

是的,它应该这样做。如果您对结果进行其他一些字符串类型操作(例如,将其与其他字符串连接、搜索字符串中的字符),您(主要)会注意到与直接打印数字的区别。

仅举个例子:

std::cout << i+i;   // should print "10"
std::cout << s+s;   // should print "55"

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:

std::cout << i+i;   // should print "10"
std::cout << s+s;   // should print "55"
久夏青 2024-11-06 17:15:17

此外,我更希望能够将相同的 int 转换为 char 数组。

char *charPtr = new char[ s.length() + 1 ] ; // s is the string in the snippet posted
strcpy( charPtr, s.c_str() ) ;

// .......

delete[] charPtr ; // Should do this, else memory leak.

Besides I would prefer if I could convert the same int to char array.

char *charPtr = new char[ s.length() + 1 ] ; // s is the string in the snippet posted
strcpy( charPtr, s.c_str() ) ;

// .......

delete[] charPtr ; // Should do this, else memory leak.
青瓷清茶倾城歌 2024-11-06 17:15:17

如果您不想再担心此类问题,您可能会对 boost/lexical_cast.hpp

#include <boost/lexical_cast.hpp>
#include <string>
#include <iostream>

int main() {
  const int i=5;
  const char* s = boost::lexical_cast<std::string>(i).c_str();
  std::cout << s << std::endl;
}

If you would like to stop worrying about issues like that you might be interested in boost/lexical_cast.hpp.

#include <boost/lexical_cast.hpp>
#include <string>
#include <iostream>

int main() {
  const int i=5;
  const char* s = boost::lexical_cast<std::string>(i).c_str();
  std::cout << s << std::endl;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文