linux字符
在linux中,字符处理 也提供C 库里的函数 。
首先当然是导入ctype.h头文件
判断
常见的,
以下单纯给出了几个函数使用的代码示例,这里不再做过多介绍。
可以直接查找man文档进行查看。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| std::string str = {"hello world \r\n"};
int i = 0; int length{str.length()}; while (i != length) { if (isalnum(str[i])) std::cout << "A - " << str[i] << " "; if (isalpha(str[i])) std::cout << "a - " << str[i] << " "; if (isblank(str[i])) std::cout << "blank - " << str[i] << " "; if (iscntrl(str[i])) std::cout << "C - " << " "; std::cout << char(10); i++; }
|
转换
在涉及转换方面,库函数就有很多门道
同样也是可以在man文档中进行查找
这里简单列出几种常用的,需要注意的。
str转换为数字
1 2 3 4 5 6
| int i = atoi("123"); long l = atol("123"); long long ll = atoll("12312312"); float f = atof("1.1234"); std::cout << sizeof(int) << " " << sizeof(long) << " " << sizeof(long long)<< char(10);
|
需要注意的点:
- 历史遗留函数 atol (在8位 ,或者16位 的系统中发挥作用) ,而在linux64 g++下 , long long 与 long 同样占用8个字节
- atof有歧义,实际上返回的是double类型
以下衔接上段代码段
1 2 3 4 5 6 7 8 9
| char* pEnd; double d = strtod("1.23456789", NULL); double d2 = strtod("-1.234567891abc", &pEnd); std::cout << pEnd << char(10); std::cout << f << char(10); std::cout << d << char(10); std::cout << d2 << char(10); printf("%f\n", d2);
|
输出可以发现 ,cout 对double 的支持不是很好,用printf,就可以多一位有效位(强一点但是不多XD
并且这样输出double ,完全达不到要求,
所以提供了ecvt 和 fcvt ,gcvt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| int decpt, sign; std::cout << ecvt(-0.123456789, 10, &decpt, &sign) << char(10); std::cout << "decpt:" << decpt << " sign:" << sign << std::endl; std::cout << ecvt(d, 10, &decpt, &sign) << char(10); std::cout << "decpt:" << decpt << " sign:" << sign << std::endl; std::cout << ecvt(d2, 10, &decpt, &sign) << char(10); std::cout << "decpt:" << decpt << " sign:" << sign << std::endl; std::cout << "__________________________\n";
std::cout << fcvt(-0.123456789, 10, &decpt, &sign) << char(10); std::cout << "decpt:" << decpt << " sign:" << sign << std::endl; std::cout << fcvt(d, 10, &decpt, &sign) << char(10); std::cout << "decpt:" << decpt << " sign:" << sign << std::endl; std::cout << fcvt(d2, 10, &decpt, &sign) << char(10); std::cout << "decpt:" << decpt << " sign:" << sign << std::endl; std::cout << "__________________________\n";
char buffer[128]; std::cout << gcvt(-0.123456789, 10, buffer) << char(10); std::cout << buffer << char(10); std::cout << gcvt(d, 10, buffer) << char(10); std::cout << buffer << char(10); std::cout << gcvt(d2, 10, buffer) << char(10); std::cout << buffer << char(10);
|