学习目标
学习掌握C++字符串转换函数
字符串转换函数包括多个函数的使用,大小写转换、字符串转数字、转double类型等
学习内容
字符串转换函数strtod atoi strupr strlwr:
strlwr小写转换、strupr大写转换
atoi:字符串转换数字,遇到非数字或结束符停止,成功返回转换数字,不成功返回0
atof:字符串转化为double类型数据
atol:字符串转化为long类型数据
atoll:字符串转化为long long类型数据
strtod:字符串转数字,带两个参数(const char*str,char**ptr),若ptr指针不为空,则会将转换数字后面其余字符地址保存在该ptr上
其余转换函数:
strtol:
strtof:
strtoll:
strtoul:
strtoull:
strtold:
学习代码
#include <iostream>
#include<cstring>
#include<iomanip>
#pragma warning(disable:4996)
using namespace std;
int main() {
//大写转换
char strr[40] = "Hello World";
strupr(strr);
cout << strr << endl;
//小写转换
strlwr(strr);
cout << strr << endl;
char num[20] = "a234^&";
int num1=atoi(num);
cout << num1 << endl;
//strtod
double d=strtod("3.1415", nullptr);
cout << d << endl;
cout << fixed << setprecision(2) << d << endl;//fixed保留小数控制,setprecision(2)即输出2位小数
//strtod(const char*,char**);
char* p;
double d1 = strtod("3.14ea", &p);
cout << d1 << endl;
cout << p << endl;
return 0;
}