在C / C ++中将字符串转换为数字
在本教程中,我们将讨论一个程序,以了解如何在C/C++中将字符串转换为数字。
C/C++提供了两种将字符串转换为数字的方法。
示例
使用sscanf()
#include<stdio.h>
int main(){
const char *str = "12345";
int x;
sscanf(str, "%d", &x);
printf("\nThe value of x : %d", x);
return 0;
}输出结果
The value of x : 12345
使用stoi()
#include <iostream>
#include <string>
using namespace std;
int main(){
string str1 = "45";
string str2 = "3.14159";
string str3 = "31337 geek";
int myint1 = stoi(str1);
int myint2 = stoi(str2);
int myint3 = stoi(str3);
cout << "stoi(\"" << str1 << "\") is " << myint1 << '\n';
cout << "stoi(\"" << str2 << "\") is "<< myint2 << '\n';
cout << "stoi(\"" << str3 << "\") is "<< myint3 << '\n';
return 0;
}输出结果
stoi("45") is 45
stoi("3.14159") is 3
stoi("31337 geek") is 31337热门推荐
10 周日徒步祝福语大全简短
11 四九节气生日祝福语简短
12 同学有弟弟祝福语简短
13 祝愿新生宝宝祝福语简短
14 城堡文案简短婚礼祝福语
15 金店立秋祝福语简短英文
16 高温祝福语短语大全简短
17 同事有趣祝福语大全简短
18 老人掉牙祝福语简短语