C++ 一个例子说明.c_str()函数

31 篇文章 10 订阅

先举个例子说明一下:

atoi()是C语言中的字符串转换成整型数的一个函数,在例子的代码里面会用到,其函数原型为:

int atoi(const char *nptr);

下面是一个C语言的代码,可以正常运行:

#include <stdio.h>
#include <stdlib.h>

int main()
{  
    char *str = "123";
	int num = atoi(str);
	printf("%d\n",num);
	getchar();
	return 0;
}

但是在C语言中使用字符串远远没有C++方便,毕竟C++提供了string类,把代码改成C++版:

//这是个错误的代码
#include <iostream>
#include <string>

using namespace std;

int main()
{  
	string str ="123";
	int num = atoi(str);
	cout<<num<<endl;
	getchar();
	return 0;
}

此时代码会报错,因为string与const char类型是不符的,前面提到,atoi()是C语言提供的函数,而C语言中没有string类,字符串使用char指针来实现的。C与C++本身就是一家,为了让它们在一定程度上可以通用,就有了.c_str()函数。我们只需要把代码修改成这样:

//这是个正确的代码
#include <iostream>
#include <string>

using namespace std;

int main()
{  
	string str ="123";
	int num = atoi(str.c_str());
	cout<<num<<endl;
	getchar();
	return 0;
}

就是在string类型的str后面加上了.c_str()函数,这也就是.c_str()的作用:
.c_str()函数返回一个指向正规C字符串的指针常量, 内容与本string串相同。因为string类本身只是一个C++语言的封装,其实它的string对象内部真正的还是char缓冲区,所以.c_str()指向了这个缓冲区并返回const。

	const _Elem *c_str() const
		{	// return pointer to null-terminated nonmutable array
		return (_Myptr());
		}
  • 11
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值