我想使用 stringstream 将整数分配给 char 指针。但是我在 ss >> p 行运行这个程序时出错。请在这里帮助我,我希望整数首先进入缓冲区,并且必须将其分配给 char*。
#include <string> // std::string
#include <iostream> // std::cout
#include <sstream> // std::stringstream
using namespace std;
int main ()
{
stringstream ss;
int n=100;
char *p;
ss << n;
ss >> p; //not working
cout << ss;
return 0;
}
最佳答案
使用 stringstream::str 获取 C++ 字符串,然后在字符串上使用 .c_str():
#include <string> // std::string
#include <iostream> // std::cout
#include <sstream> // std::stringstream
using namespace std;
int main ()
{
stringstream ss;
int n = 100;
char* p;
ss << n;
string tmp = ss.str();
p = const_cast<char*>(tmp.c_str());
cout << "p: " << p << '\n';
return 0;
}
请注意,一旦字符串超出范围,char 指针就会失效。如果您需要某种工厂函数行为,按值返回一个字符串,使用 strlcpy 或者 new 和 shared_ptr。
关于c++ - 使用 stringstream 将整数分配给 char 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41698355/