一, string 转化为数字
1. 使用 stoi
#include #include using namespace std; int main() { string str = "123"; int a = stoi(str); cout <<a; str = "123.44"; double b = stod(str); cout << b; return 0; } /* stoi 如果是非法输入: 1. 会自动截取最前面的数字, 直到遇到不是数字为止 (所以说如果是浮点型, 会截取前面的整数部分) 2. 如果最前面不是数字, 会运行时发生错误 */ /* stod 如果是非法输入: 1. 会自动截取最前面的浮点数, 直到遇到不满足浮点数为止 2. 如果最前面不是数字或者小数点, 会运行时发生错误 3. 如果最前面是小数点, 会自动转化后在前面补 0 */ /* 相应的还有: stof(string to float) stold(string to long double) stol(string to long) stoll(string to long long) stoul(string to unsigned long) stoull(string to unsigned long long) */
2. 使用 stringstream
#include #include using namespace std; int main() { string str = "1234"; stringstream stream; stream << str; int a; stream>> a; cout <<a; return 0; } /* 如果转 int 是非法输入: 1. 会自动截取最前面的数字, 直到遇到不是数字为止 (所以说如果是浮点型, 会截取前面的整数部分) 2. 如果最前面不是数字, 会转化为整数 0 */ /* 如果转 double 是非法输入: 1. 会自动截取最前面的浮点数, 直到遇到不满足浮点数条件为止 2. 如果最前面不是数字或者小数点, 会转化为整数 0 3. 如果最前面是小数点, 会转化为浮点数后在前面自动补 0 */ /* 其他数字类型也可以转化 */
注意: sscanf,sprintf,atoi 操作对象为 字符数组 (char c[])
3. 如果使用的不是 string 类, 而是字符数组 char c[]
1使用 sscanf
#include #include using namespace std; int main() { char c[50] = "123"; int a; sscanf(c, "%d", &a); // 不要忘记 "&" int b = 567; sprintf(c, "%d", b); cout << a << endl << c; return 0; } /* sscanf 将字符数组转换为数字, 输入到数字变量中 sprintf 将数字转换为字符数组, 输出到字符数组变量中 */
2使用 atoi / atol / atoll
#include #include using namespace std; int main() { char c[50] = "123"; int a = atoi(c); cout << a; return 0; }
二, 数字转化为 string
1. 使用 to_string
#include #include using namespace std; int main() { int a = 123; string s = to_string(a); cout << s; return 0; }
2. 使用 stringstream
#include #include using namespace std; int main() { stringstream stream; string str; int a = 123; stream << a; stream>> str; cout << str; return 0; }
3. 如果是字符数组 (使用 sprintf)
#include #include using namespace std; int main() { char c[50] = "123"; int a; sscanf(c, "%d", &a); // 不要忘记 "&" int b = 567; sprintf(c, "%d", b); cout << a << endl << c; return 0; } /* sscanf 将字符数组转换为数字, 输入到数字变量中 sprintf 将数字转换为字符数组, 输出到字符数组变量中 */
参考: http://c.biancheng.net/view/1527.html
来源: http://www.bubuko.com/infodetail-3149106.html