c 串转string_C++的字符串怎么转换成C字符串?

写C++字符串,你想不想用一个函数直接把string类字符串直接转换成int?反正我整天都像这样,要不然就要写stringstream,光听着名字都绕口

#include

#include

using namespace std;

int str2int(string str)

{

stringstream res;

res << str;

int ans;

res >> ans;

return ans;

}

int main()

{

string s = "123";

int ans = str2int(s);

return 0;

}

这样是我通常转换的方式,当然还有一种C的方式,循环解决

string str="123";

int ans = 0;

for (int i = 0; i < str.size(); i++)

{

ans = ans * 10 + str[i] - '0';

}

那么有没有行数短的函数可以直接调用呢,答案是肯定的!

atoi()函数

这是一个C库的函数,需要用到头文件

#include

以下是atoi函数的声明

int atoi(const char *str)

示例如下:

#include

#include

#include

int main()

{

int val;

char str[20];

strcpy(str, "98993489");

val = atoi(str);

printf("字符串值 = %s, 整型值 = %d\n", str, val);

strcpy(str, "runoob.com");

val = atoi(str);

printf("字符串值 = %s, 整型值 = %d\n", str, val);

return(0);

}

当然这是C语言的写法,C++也可以用,但是C++有更好的办法——string类,但是你可以把字符数组换成string,你就会发现运行不了,是因为C语言不支持string,所以换成string需要一个.c_str()方法,实例代码如下

#include

#include

using namespace std;

int main()

{

string s = "123";

int ans = atoi(s.c_str());

return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值