1,定义及初始化
为了对比char【字符串数组】和string【STL容器】:
定义一个字符串数组a,长度为100,并初始化字符串“Hello world!”,
定义一个string变量s,并初始化字符串“Hello world!”。
#include <bits/stdc++.h>
using namespace std;
int main(){
char a[105]="Hello world!";
string s="Hello world!";
cout<<a<<endl<<s<<endl;
return 0;
}
2,接收带空格字符串
为了对比char【字符串数组】和string【STL容器】:
全局定义一个字符串数组a,长度为100,
全局定义一个string变量s。
使用a接收一个带空格字符串,并输出,
使用s接收一个带空格字符串,并输出。
#include <bits/stdc++.h>
using namespace std;
char a[105];
string s;
int main(){
cin.getline(a,sizeof(a));
cout<<a<<endl;
getline(cin,s);
cout<<s;
return 0;
}
为了对比char【字符串数组】和string【STL容器】:
全局定义一个字符串数组a,长度为10000,
全局定义一个string变量s。
使用a接收一个可能带空格、换行的字符串,使用‘#’作为结束标记,并输出,最后加换行,
使用s接收一个可能带空格、换行的字符串,使用‘$’作为结束标记,并输出,最后加换行。
#include <bits/stdc++.h>
using namespace std;
char a[10005];
string s;
int main(){
cin.getline(a,sizeof(a),'#');
cout<<a<<endl;
getline(cin,s,'$');
cout<<s;
return 0;
}
更多请看下集:char与string的区别(2)
2921

被折叠的 条评论
为什么被折叠?



