C++ | 常用语法笔记
判断数字还是字母
1.笨办法,使用直接判断办法
if(c >= '0' && c <= '9') cout << "c是数字" << endl;
if(c >= 'a' && c <= 'z') cout << "c是小写字母" << endl;
if(c >= 'A' && c<= 'Z') cout << "c是大写字母" << endl;
2.使用 isdigit() 和 isalpha()函数
是检查字符的ASCII值,返回true还是false
if(isdigit(c)) if( isalpha(c))
字符(char/string)与整型(int)相互转换
1.char 转换 int
char c = '6';
int num = c - '0';
2.int 转换 char
int num = 5;
char c = num + '0';
3.string 转换 int 或 float
stoi | atoi | stof | atof
#include <cstring> // 头文件string str = "1234";
int n = stoi(str); // n = 1234,转换失败会发生异常
int n = atoi(str); // n = 1234,转换失败会返回0string str = "1234.12";
double d = stof(str); // d = 1234.12,转换失败会发生异常
double d = atof(str); // d = 1234.12,转换失败会返回0
4.int 转换 string
to_string
#include <string> // 头文件int num = 1234;
string str = to_string(num); // str = "1234"