字符串数组的使用:
1. 字符串数组的定义: 指针 + 一维数组:const char* season[] = { "Spring", "Summer", "Fall", "Winter" }。season中每个元素都是一个指针。
2. 调用字符串数组中的每一个字符。season[0] = "Spring";
// chapter7.8.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
// 定义字符串数组(* array[], 指针加一维数组)
const int num = 4;
const char* season[num] = { "Spring", "summer", "Fall", "Winter" };
struct Expense{
double expense[num];
};
void fill_array(Expense& e, const int n) {
for (int i = 0; i < n; i++) {
// 字符串数组的使用, 如何调用字符串数组中的一个字符串
cout << "Enter " << season[i] << " expense:" << endl;
cin >> e.expense[i];
}
}
void show_array(const Expense e, const int n) {
for (int i = 0; i < n; i++) {
cout << season[i] << ":\t";
cout << e.expense[i] << endl;
}
}
int _tmain(int argc, _TCHAR* argv[]) {
Expense exp = { { 0 } };
fill_array(exp, num);
show_array(exp, num);
return 0;
}
// lesson5.20.cpp : Defines the entry point for the console application.
// 二位数组的几种形式
#include "stdafx.h"
#include <iostream>
using namespace std;
const int Cities = 5;
const int Years = 4;
int _tmain(int argc, _TCHAR* argv[]) {
// 字符串数组
const char* cities[Cities] = {
"Gribble City",
"Gribbletown",
"New Gribble",
"San Gribble",
"Gribble vista"
};
int maxTemperature[Years][Cities] = {
{ 96, 100, 87, 101, 105 },
{ 96, 98, 91, 107, 104 },
{ 97, 101, 93, 108, 107 },
{ 98, 103, 95, 109, 108 }
};
cout << "Maximum temperature for 2008-2011:" << endl;
for (int i = 0; i < Cities; i++) {
cout << cities[i] << ":\t";
for (int j = 0; j < Years; j++) {
cout << maxTemperature[j][i] << "\t";
}
cout << endl;
}
return 0;
}