concatenate char with int
I have to concatenate char with int. Here's my code:
int count = 100;
char* name = NULL;
sprintf((char *)name, "test_%d", count);
print开发者_StackOverflow社区f("%s\n", name);
Nothing printed. What's the problem?
You didn't allocate any memory into which sprintf
could copy its result. You might try:
int count = 100;
char name[20];
sprintf(name, "test_%d", count);
printf("%s\n", name);
Or even:
int count = 100;
char *name = malloc(20);
sprintf(name, "test_%d", count);
printf("%s\n", name);
Of course, if your only goal is the print the combined string, you can just do this:
printf("test_%d\n", 100);
If you programm C++ use sstream instead:
stringstream oss;
string str;
int count =100
oss << count;
str=oss.str();
cout << str;
You have to allocate memory for name
first. In C, library functions like sprintf
won't make it for you.
In fact, I am very surprised that you didn't get a segmentation fault.
A simple workaround would be using char name[5+11+1]
for the case of 32-bit int
.
I use boost::format
for this.
#include <boost/format.hpp>
int count = 100;
std::string name = boost::str( boost::format("test_%1%") % count );
Since the answer is tagged C++, this is probably how you should do it there:
The C++11 way: std::string str = "Hello " + std::to_string(5);
The Boost way: std::string str = "Hello " + boost::lexical_cast<std::string>(5);
#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();
精彩评论