示例:
#include <stdio.h>
#include <string>
using namespace std;
int main()
{
string a;
a.resize(100); //需要预先分配空间
scanf("%s", &a[0]);
printf("%s\n", a.c_str());
return 0;
}
成员函数:
c_str | 得到等效的C字符串数据 |
data | 得到等效的字符串数组 |
get_allocator | 得到分配器 |
copy | 从字符串中复制字符序列 |
find | 查找字符 |
rfind | 从后向前查找字符 |
find_first_of | 查找某个字符第一次出现的位置 |
find_last_of | 查找某个字符最后一次出现的位置 |
find_first_not_of | Find absence of character in string |
find_last_not_of | Find absence of character in string from the end |
substr | 生成子字符串 |
compare | 比较 |
例题:成绩排序
使用scanf和printf进行输入输出
#include <stdio.h>
#include <algorithm>
#include <string>
using namespace std;
struct stu
{
int grade;
string name;
int order;
};
bool CmpAscend(stu x,stu y)
{
if(x.grade == y.grade)
return x.order < y.order;
return x.grade < y.grade;
}
bool CmpDescend(stu x,stu y)
{
if(x.grade == y.grade)
return x.order < y.order;
return x.grade > y.grade;
}
int main()
{
int m,n;
while(scanf("%d %d",&m,&n) != EOF)
{
stu sss[m];
for(int i=0;i<m;i++)
{
sss[i].name.resize(30); //需要预先分配空间
scanf("%s %d",&sss[i].name[0],&sss[i].grade);
sss[i].order = i;
}
if(n==1)
{
sort(sss,sss+m,CmpAscend);
}
else
{
sort(sss,sss+m,CmpDescend);
}
for(int j=0;j<m;j++)
{
printf("%s %d\n",sss[j].name.c_str(),sss[j].grade); //成员函数c_str()
}
}
return 0;
}