对于数字,int 转string时经常需要补0,比如 日期0201,2月1日。或序列号0001。
int n_zero = 4;//总共多少位
string old_string = "2";
std::string new_string = std::string(n_zero - old_string.length(), '0') + old_string;
注意不要让n_zero小于 old_string长度,否则unsigned int 会让你崩溃。
c++ - Add leading zero's to string, without (s)printf - Stack Overflow
对于数字,int转string时经常需要补0,比如日期0201,2月1日。或序列号0001。int n_zero = 4;string old_string = "2";std::string new_string = std::string(n_zero - old_string.length(), '0') + old_string;注意不要让n_zero小于 old_string长度,否则unsigned int会让你崩溃。https://stackoverfl...
功 能:把一
字符串
转
换为整数
用 法:int atoi(const char *nptr);
详细解释:atoi是英文array to integer 的缩写。atoi()会扫描参数nptr
字符串
,如果第一个字符不是
数字
也不是正负号返回零,否则开始做类型
转
换,之后检测到非
数字
或结束符 /0 时停止
转
换,返回整型数。 参 数:
*nptr: 待
转
化的
字符串
。
int:
转
换后的整形数。
2、atol
功 能:把一
字符串
转
换为长整形
用 法:long atol(const char *nptr);
详细解释:atol()会扫描参数nptr字符
int n = 3;
string
s = n.To
String
().PadLeft(4, '0'); //0003
s =
string
.Format("{0:d4}", n); //0003
int i=10;
方法1:Console.WriteLine(i.To
String
("D5"));
方法2:Console
char b[] = "xxxx";
//先计算需要
补
0的长度,
补
零后并输出
字符串
。
sprintf(a, "%0*d%s", 15 - strlen(b), 0, b);
qDebug() << a; //00000000000xxxx
int c = 4;
int n = 3;
sprintf(a, "%0*d", n, c);
qDebug() << a.
int num = 123;
string
num2str = to_
string
(num);
cout << typeid(to_
string
(num) == typeid(
string
) << endl; // true
1.2 float/double型
数字
转
字符串
(不
补
0)
#include<sstream
string
stream ss; //定义一个
string
stream变量,需要包含头文件 include<sstream>
string
str="helloWorld";
string
res;
在这个示例中,我们使用了 `std::
string
stream` 类从
字符串
中读取
数字
,并将其存储在 `int` 类型的变量 `num` 中。最后,我们将变量 `num` 的值输出到屏幕上。
请注意,如果
字符串
无法
转
换为
数字
,那么 `ss >> num` 的结果将为 false。