c++中 关于字符串的一些需要注意的问题

c++中的字符串其中一种是从C语言中继承过来的,C语言中的字符串是char类型的数组,

 定义

  char a[20]="I am a boy“;

输出

  cout<<a;

但是这种字符串不可以直接赋值,比如再定义一个字符数组 b[20],且给b赋值:b[20]=a[20];

这是编译器不会显示错误,但是输出会有错误,虽然这样,但是有时候我们要注意了

   当结构体中有字符数组的时候

#include <iostream>
using namespace std;
struct birthday
{
 int day;
 int month;
 int year;
};
struct student
{
 int num;
 char name[10];
 birthday shengri;
}; 
int main()
{
 student s1={01,"xiaozhong",{10,10,89}};
 student s2;
 cout<<s1.num<<' '<<s1.name<<' '<<s1.shengri.day<<' '<<s1.shengri.month
     <<' ' <<s1.shengri.year<<endl;
    s2=s1;
    cout<<s2.num<<' '<<s2.name<<' '<<s2.shengri.day<<' '<<s2.shengri.month
     <<' ' <<s2.shengri.year<<endl;
    return 0;
}

这时候就是可以的

  当类中的数据成员有字符数组的时候

// Note:Your choice is C++ IDE
#include <iostream>
#include <cstring>
using namespace std;
class String
{
 private:
  enum {SZ=80};
  char str[SZ];
 public:
  String()
   {str[0]='/0';}
  String(char s[])
   {strcpy(str,s);}
  void display()
    {cout<<str;}
  void concat(String s2)
   {if(strlen(str)+strlen(s2.str)<SZ)
     strcat(str,s2.str);
    else
     cout<<"/nString too long ";
   }
};  
int main()
{
  String s1("merry christmas!");
  String s2="season's greetings!";
  String s3;
  cout<<"/ns1="; s1.display();
  cout<<"/ns2="; s2.display();
  cout<<"/ns3="; s3.display();
   s3=s1;
   cout<<"/ns3="; s3.display();
   s3.concat(s2);
   cout<<"/ns3="; s3.display();
   cout<<endl; 
    return 0;
}

这时候也是可以的

所以字符串在应用的时候,我们应该加以区分。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值