函数和string类对象
前言
浮躁的人容易问:我到底应该学什么;别问,学就对了。
C风格字符串和string对象的用途几乎相同,但与数组相比,string对象可以实现传递与复制的功能。
一、一个小型示例
#include<iostream>
#include<string>
using namespace std;
const int SIZE = 5;
void display(const string sa[], int n);
int main()
{
string list[SIZE];
cout << "Enter " << SIZE << " favorite food: " << endl;
for (int i = 0; i < SIZE; i++)
{
cout << i + 1<<":";
getline(cin, list[i]);//用getline函数可捕获空格
}
cout << "Your list:" << endl;
display(list,SIZE);
return 0;
}
void display(const string sa[], int n)//该函数用来显示列表内容
{
int i;
for (i = 0; i < n; i++)
{
cout << i + 1 << ":" << sa[i] << endl;
}
}
其中,数组中的每个元素都是一个string对象,形参sa是一个指向string对象的指针,sa[i]是一个string对象。