我必须将char与int连接起来。 这是我的代码:
int count = 100;
char* name = NULL;
sprintf((char *)name, "test_%d", count);
printf("%s\n", name);
什么都没打印。有什么问题?
答案 0 :(得分:5)
您没有分配sprintf
可以复制其结果的任何内存。你可以试试:
int count = 100;
char name[20];
sprintf(name, "test_%d", count);
printf("%s\n", name);
甚至:
int count = 100;
char *name = malloc(20);
sprintf(name, "test_%d", count);
printf("%s\n", name);
当然,如果你唯一的目标是打印组合字符串,你可以这样做:
printf("test_%d\n", 100);
答案 1 :(得分:2)
如果你编程C ++而不是使用sstream:
stringstream oss;
string str;
int count =100
oss << count;
str=oss.str();
cout << str;
答案 2 :(得分:1)
您必须先为name
分配内存。在C中,像sprintf
这样的库函数不适合你。
事实上,我很惊讶您没有遇到分段错误。
对于32位char name[5+11+1]
的情况,一个简单的解决方法是使用int
。
答案 3 :(得分:0)
我为此使用了boost::format
。
#include <boost/format.hpp>
int count = 100;
std::string name = boost::str( boost::format("test_%1%") % count );
答案 4 :(得分:0)
由于答案标记为C ++,这可能是你应该在那里做的:
C ++ 11方式:std::string str = "Hello " + std::to_string(5);
推动方式:std::string str = "Hello " + boost::lexical_cast<std::string>(5);
答案 5 :(得分:0)
#include <iostream>
#include <string>
#include <sstream>
int count = 100;
std::stringstream ss;
ss << "Helloworld";
ss << " ";
ss << count ;
ss << std::endl;
std::string str = ss.str();
std::cout << str;
const char * mystring = str.c_str();