简体   繁体   English

使用 sprintf_s() 后如何将 char* 重新转换为 integer?

[英]How to re-cast char* to integer after using sprintf_s()?

This is my casting from int to char*:这是我从 int 到 char* 的转换:

char* str = malloc(sizeof("0000"));
int int_ = 10;
sprintf_s(str, sizeof("0000"), "%04d", int_);
//str == "0010"

And I want to re-cast str to int back ( int_new == 10 ).我想将str重新转换为 int ( int_new == 10 )。 How could I do this?我怎么能这样做?

Use strlen to find the size of a string.使用 strlen 查找字符串的大小。 Remember to add +1 for the nul byte at the end of the string.请记住在字符串末尾为 nul 字节添加 +1。 Otherwise, snprintf will fail.否则,snprintf 将失败。

int max_size = 5 ;
char* str = malloc(max_size);
int int_ = 10;
sprintf_s(str, max_size, "%04d", int_);

int int_new = atoi(str) ;

Alternative选择

int int_ = 10;

char buff[32] ;   // make it big enough to worst case
snprintf(buff, sizeof(buff), "%04d", int_) ;
char *str = strdup(buff) ;

int int_new = atoi(str) ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM