题目及答案链接
https://www.liuchuo.net/archives/1888
c++ 有关 字符串 和各种类型的转换
- #include <string>
- string a;
- a=to_string(b); //b 可以是 任何基础 [数值] 类型 不包括 char
- #include <cstdlib>
- valT=atox(b) //x 可以换成 i l f,b 必须是 char * 类型; 因为这个函数是从 c 来的. b 必须是符合转换的字符串
- //atox 是 ascii to x 的意思, atoi 字符串转整形, atol 串转长整, atof 串转 double
- valT=strtox(char*a,char**endptr,base) //x 可以是 l ul d , 算是 atox 的改良版, strtol 串转 long int ,strtoul 串转无符 long , strtod 串转 double
- // 第一个参数和 atox(b) 的 b 类似, 是字符串, 不要求串全部都是要转换的内容 (没有符合子串返回 0)
- // 第二个参数是可以为 NULL, 或者 char * 变量的 [地址] , 注意是 char * 变量的地址, 不是 char*,null 则函数无视 null, 否则 * endptr 指向
不合条件而终止的字符串中的字符指针, 例如串为 "abc123def"; 则函数运行完 endptr 指向'd'的位置 (已经展示了相对于 atox 的优点)
例: char* a,*b; strtol(a,&b,10);
// 第三个参数是 base, 表示用什么进制解释 串中的数字, 输出还是十进制, 若 base 为 0 则自动匹配, 一般都是 10
string ,char*,char[],const char* 之间的转化
string 转 char*.
- //string st;
- char* c=(char*)st.date();
- const char* b=st.date();
- const char* b=st.c_str()
string 转 char[]
- //char b[x];string st;
- st.copy(b, 个数 n, 起始下标);
b[n]='\0';[注意, 复制完后, b 只是字符数组, 要手动在最后添加'\0'使其成为字符串]
或者手动 for 循环挨个赋值
char * char[] 转 string
直接赋值即可
来源: http://www.bubuko.com/infodetail-2995769.html