string转int/float/double、int/float/double转string、转字符串数组的方法:stoi、stringstream、scanf、to_string、sprintf

一、string转化为数字

1.使用stoi


#include <iostream>
#include <string>
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 <iostream>
#include <sstream>
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[]

①使用 sscanf

#include <iostream>
#include <cstdio>
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将数字转换为字符数组,输出到字符数组变量中
*/

②使用 atoi / atol / atoll

#include <iostream>
#include <string>
using namespace std;
int main() {
    char c[50] = "123";
    int a = atoi(c);
    cout << a;
    return 0;
}

二、数字转化为string

1.使用to_string

#include <iostream>
#include <sstream>
using namespace std;
int main() {
    stringstream stream;
    string str;
    int a = 123;
    stream << a;
    stream >> str;
    cout << str;
    return 0;
}

2.使用stringstream


#include <iostream>
#include <sstream>
using namespace std;
int main() {
    stringstream stream;
    string str;
    int a = 123;
    stream << a;
    stream >> str;
    cout << str;
    return 0;
}

3.如果是字符数组(使用sprintf)


#include <iostream>
#include <cstdio>
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将数字转换为字符数组,输出到字符数组变量中
*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值