这个还是用的稍稍比较多的,记录一下
1、数字类型转字符串
C++ 版本
int转换成string
用to_string(int/long/double/....)函数
string s=to_string(1);
C 语言版本
提供了几个标准库函数,可以将任意类型(整型、长整型、浮点型等)的数字转换为字符串,下面列举了各函数的方法及其说明。(C98)
● itoa():将整型值转换为字符串。
● ltoa():将长整型值转换为字符串。
● ultoa():将无符号长整型值转换为字符串。
● gcvt():将浮点型数转换为字符串,取四舍五入。
● ecvt():将双精度浮点型值转换为字符串,转换结果中不包含十进制小数点。
● fcvt():指定位数为转换精度,其余同ecvt()。
除此外,还可以使用sprintf系列函数把数字转换成字符串,其比itoa()系列函数运行速度慢
#include<stdio.h>
int main()
{
char buffer[10];
char *a = "1234";
char *b = "5678";
sprintf(buffer, "%s%s", a, b);
printf("%s\n", buffer);
return 0;
}
2、字符串类型转数字
C 语言版本
提供了几个标准库函数,可以将字符串转换为任意类型(整型、长整型、浮点型等)。
● atof():将字符串转换为双精度浮点型值。
● atoi():将字符串转换为整型值。
● atol():将字符串转换为长整型值。
示例:
string s("12");
int m = atoi("12"); // 把 char* 字符串转换为int型
int n = atoi(s.c_str()); // 把 string 字符串转换为int型
还有 sscanf
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *string;
int digit;
char buf1[255];
char buf2[255];
/*1.最简单的用法*/
string = "china beijing 123";
sscanf(string, "%s %s %d", buf1, buf2, &digit);
printf("%s %s %d", buf1, buf2, digit);//china beijing 123
return 0;
}
C++ 版本
C++ 11 后有自己的转换函数
C++11 - std::string - stod/stof/stoi/stol/stold/stoll/stoul/stoull_std::stod-CSDN博客
或者使用第三方库 boost 的模板进行转换
int a = boost::lexical_cast<int>("1");
3. c#补充
//字符转数字
string str = "100";
int a = int.Parse(str);
double b = Convert.ToDouble(str);
//标准类型转换都有,标准类型.Parse函数转换为该类型,以及Convert.标准类型来转换
//数字转字符
int a = 100;
double b = 100;
string str = a.ToString();
string str = b.ToString();
//标准类型都有标准类型.ToString转换为字符串