开发者社区> 问答> 正文

C++字符串问题,char type[10]跟string type 有什么区别?

这是在刘汝佳的书上的一道例题,我做的时候遇到了一个问题,我是新手,请指点。

#include
using namespace std;
int m,n;
int a[100000+10];
int main(){
int shift_circular_left(int,int);
int shift_circular_right(int,int);
int find(int);
cin>>m>>n;

for(int i=1;i<=m;++i){
a[i]=i;
}
char type[10]; //在这一行定义的时候为什么用string type会错?

int x,y,p,q;
for(int i=0;i scanf("%s%d%d",type,&x,&y);
p=find(x);
q=find(y);
if(type[0]=='A'){
if(q>p)shift_circular_left(p,q-1);
else shift_circular_right(p,q);
}
else{
if(p<q)shift_circular_left(p,q);
else shift_circular_right(q+1,p);
}
}
for(int i=1;i<=m;++i){

cout<<a[i]<<' ';
}
return 0;
}
int shift_circular_left(int x,int y){
int t=a[x];
for(int i=x;i<=y-1;++i){
a[i]=a[i+1];
}
a[y]=t;
}
int shift_circular_right(int x,int y){
int t=a[y];
for(int i=y;i>=x+1;--i){
a[i]=a[i-1];
}
a[x]=t;
}
int find(int x){
for(int i=0;i<=m;++i){
if(a[i]==x)return i;
}
}

在定义type的时候,为什么必须用字符数组,不能用字符串类型?

展开
收起
a123456678 2016-03-04 10:51:39 2543 0
1 条回答
写回答
取消 提交回答
  • string 对象是堆内存。char s[10];是栈内存 ,所以scanf是不行的,他是需要构造的或者说用c++中的cin 也可以啊....

    #if 1
    #include 
    #include 
    using namespace std;
    
    int main()
    {
    string s;
    cin >> s;
    cout << s;
    return 0;
    }
    #endif

    其实最重要的一点是string 类型的对象 你永远都不知道他的成员变量指向哪里。那么你直接输入肯定会出问题,

    2019-07-17 18:51:56
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
使用C++11开发PHP7扩展 立即下载
GPON Class C++ SFP O;T Transce 立即下载
GPON Class C++ SFP OLT Transce 立即下载

相关实验场景

更多