2011-10-14 41 views
1

我必須連接字符與int。 這裏是我的代碼:連接字符與int

int count = 100; 
char* name = NULL; 
sprintf((char *)name, "test_%d", count); 
printf("%s\n", name); 

沒有打印。有什麼問題?

+6

您需要爲'name'分配一些存儲空間 –

+5

請指定您正在使用的編程語言。 C和C++在解決這個共同的問題上有很多不同的成語。 –

+0

@Rob:假設他會接受使用任何一種語言的成語的答案是不安全的嗎? –

回答

1

您必須首先爲name分配內存。在C中,庫函數sprintf不會爲你做。

事實上,我很驚訝,你沒有得到分段錯誤。

對於32位int的情況,一個簡單的解決方法是使用char name[5+11+1]

+0

像「snprintf」這樣的「重」庫函數往往會進行大量的錯誤檢查,而不是像「memcpy」這樣的「輕量級」函數。 –

+0

@Dietrich:也許你是對的,但它很奇怪。 [documentation](http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/)堅持認爲_作爲str傳遞的數組的大小應該足以包含整個格式化的string_並且不是特例空指針。 – Vlad

+0

'int'可以達到11個數字:-2147483648(在32位) –

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); 
+0

在32位機器上,陣列不需要超過[17]。 –

+0

是的。我必須比@MooingDuck更懶。 –

2

如果您程序C++使用sstream代替:

stringstream oss; 
string str; 
int count =100 

oss << count; 
str=oss.str(); 

cout << str; 
+0

您不檢查流操作是否成功。 –

+0

'stringstream << int'失敗而沒有拋出異常? (不是說你不應該檢查) –

0

爲此我使用boost::format

#include <boost/format.hpp> 

int count = 100; 
std::string name = boost::str(boost::format("test_%1%") % count); 
0

由於答案被標記C++,這可能是你應該怎麼做有:

的C++ 11路:std::string str = "Hello " + std::to_string(5);

升壓方式:std::string str = "Hello " + boost::lexical_cast<std::string>(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();