string操作大全

1. string to int && int to string

2. 整数1转换成字符串"001"

int sprintf ( char * str, const char * format, ... );
int snprintf ( char * s, size_t n, const char * format, ... );
n
Maximum number of bytes to be used in the buffer.
The generated string has a length of at most n-1, leaving space for the additional terminating null character.
size_t is an unsigned integral type.

// use sprintf
int i = 8;
char array[4];
sprintf(array, "%.3d", i);
string s = array;

// use stringstream
int i = 8;
stringstream ss;
ss << std::setw(3) << std::setfill('0') << i;
string s = ss.str();

 3. strncpy

char * strncpy ( char * destination, const char * source, size_t num );

 

参考资料:

https://stackoverflow.com/questions/5590381/easiest-way-to-convert-int-to-string-in-c

Convert a number to a string with specified length in C++

string 与char* char[]之间的转换

posted @ 2014-11-10 11:36  Sawyer Ford  阅读(200)  评论(0编辑  收藏  举报