c++中怎么把一个字符串赋给一个变量

来源:百度知道 编辑:UC知道 时间:2024/05/16 15:06:46
1.我想把一个字符串赋给一个变量,不知怎么弄.输出呢?
2.字符串数组如何得到.例如str[5]是一个字符串的数组,现在想在str[1]中存储"ABC",在str[2]中存储"ABCDE",在str[3]中存储"ABCDEF"....请问像这样的赋值和输出应该怎么实现呢?
谢谢!

问题一的解决:
这个问题通常有两种解决方法,一个是字符数组(现已不常用)另一个是string类,当然这个要在头文件中加上#include<string>
代码如下:
#include<iostream>
#include<string>
using namespace std;]
int main(){
string str="abcd";
cout<<str;
}
或者是
#include<iostream>
using namespace std;
int main(){
char *ch="abc";
cout<<ch;

}
或者是
#include<iostream>
using namespace std;
int main(){
char ch[3]="abc"; //〔〕中可以是3也可以是其它任意数
cout<<ch;
}
问题二的解决:
定义数组时用定义或用结构体或类来解决
#include<iostream>
using namespace std;
int main(){
string str[3];
for(int i=0;i<3;++i)
cin>>str[i];
for(int i=0;i<3;++i)
cout<<str[i];
}

可以使用:
strcpy(str, "ABC");strcpy(str,"ABCDE");
但是有一点要注意,str的空间大小要够存放后面的字符串.
这样就可以把ABC赋值给str了.
包含头文件:
#include