C++定义字符串数组的方法

总结:将数组元素类型最好定义为string类型,而不是char*类型(VS2017无法通过)


#include <iostream>
using namespace std;

int main()
{
	char* const a[7] = { "Hello", "world" };    
	//会出现[Warning] deprecated conversion from string constant to 'char*' [-Wwrite-strings]
	//Dev编译器下:极不赞成 、强烈反对上面这种定义方式 
	//在VS2017下,则编译不会 通过 
	char  b[7][10] = { "A sunny", "day!" };
	cout<<a[0]<<endl;
	cout<<b[1]<<endl; 
	char* c=b[1];
	cout<<c<<endl;
	return 0;
}```

比较好的方法:用string类型
#include<string>
#include<iostream>
int main()
{
using namespace std;
string str[3] = {"ert","asd", "cvb"};
for(int i = 0; i < 3; i ++)
{
cout<<str[i]<<endl;
}
}
运行这段程序就可以了,是在vs2008上测试过。注意两个地方
1.#include<string>
2.using namespace std;
千万不要include string.h啦,string.h是C里的字符串库,而string是C++库,两者没有关系。这要弄明白连个库有什么不同,在网上搜搜就有。
C++里的String是包含在std命名空间里的,所以要加上第二句。
//部分来源:https://zhidao.baidu.com/question/424851168.html
  • 8
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值