string数组访问

lee_longerlonger 2009-04-01 12:46:42
#include<iostream>
using namespace std;

int main()
{
string * str1 = new string[10];
*str1 = "china";
*(str1+1)="janpan";
*(str1+9)="Kearo";
cout<<str1<<endl; //不能输出“china”
return 0;
}
...全文
99 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
string跟C-串不一样~~
去翻翻资料
liumingrong 2009-04-01
  • 打赏
  • 举报
回复
ostream并没有对string*类型进行operator<<重载,只会输出指针的值,也就是数组的首地址
能对char*的数组进行输出,是因为对它进行了重载
chin_chen 2009-04-01
  • 打赏
  • 举报
回复
string * str1 = new string[10];
stcpy(str,"china");
lizhi110110110 2009-04-01
  • 打赏
  • 举报
回复
string * str1 = new string[10];
stcpy(str,"china");
这样就可以了
flameearth 2009-04-01
  • 打赏
  • 举报
回复
cout<< str[0] << endl;
lpf000 2009-04-01
  • 打赏
  • 举报
回复
[Quote=引用 7 楼 wanjingwei 的回复:]
引用 6 楼 mmoaay 的回复:
C/C++ code#include"iostream"
#include"string"
using namespace std;

int main()
{
string* str1=new string[10];
*str1="china";
*(str1+1)="janpan";
*(str1+9)="Kearo";
for(int i=0;i <10;i++)
cout < <*(str1+i) < <endl;
return 0;
}


可以输出三个



不行啊,提示error C2679: binary ' < <' : no operator defined …
[/Quote]
我怎么可以输出
是不是你复制了代码?你有没注意插入操作符 中间有空格?
beyond071 2009-04-01
  • 打赏
  • 举报
回复
如果不重载运算符operator << ,可以使用如下方式:
cout <<str1->c_str() <<endl;

string类型提供了用于和C API接口的转换函数c_str()。
它可以返回一个const char*指针,其中内容就是string存放的字符串。
Paradin 2009-04-01
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 zbing0203 的回复:]
cout < <(*str1) < <endl;
[/Quote]
d
wanjingwei 2009-04-01
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 mmoaay 的回复:]
C/C++ code#include"iostream"
#include"string"
using namespace std;

int main()
{
string* str1=new string[10];
*str1="china";
*(str1+1)="janpan";
*(str1+9)="Kearo";
for(int i=0;i<10;i++)
cout<<*(str1+i)<<endl;
return 0;
}


可以输出三个

[/Quote]

不行啊,提示error C2679: binary '<<' : no operator defined which takes a right-hand operand of type 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >'
T技术沙龙 2009-04-01
  • 打赏
  • 举报
回复
#include"iostream"
#include"string"
using namespace std;

int main()
{
string* str1=new string[10];
*str1="china";
*(str1+1)="janpan";
*(str1+9)="Kearo";
for(int i=0;i<10;i++)
cout<<*(str1+i)<<endl;
return 0;
}

可以输出三个
chin_chen 2009-04-01
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 chin_chen 的回复:]
string * str1 = new string[10];
stcpy(str,"china");
[/Quote]

看错了。
zbing0203 2009-04-01
  • 打赏
  • 举报
回复
cout <<(*str1) <<endl;

65,210

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧