while, ex6.12

版权声明:自由转载-非商用-非衍生-保持署名 | Creative Commons BY-NC-ND 4.0

Example

将一个数组拷贝到另一个数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>

using std::cin;
using std::cout;
using std::endl;


int ()
{
int arr[5] = { 1, 2, 3, 4, 5 };
int *source = arr;
size_t sz = sizeof(arr) / sizeof(*arr);
int *dest = new int[sz];
while (source != arr + sz)
{
*dest++ = *source++;
}


int *dp = dest - sz;
for (size_t i = 0; i < sz; ++i)
{
cout << *dp << endl;
dp++;
}
return 0;
}

outputs

1
2
3
4
5
1
2
3
4
5

Exercise 6.12

输入一些单词,统计里面单词出现的次数。

如:how, now now now brown cow cow
则需输出: how 1次,now 3次,brown 1次,cow 2次

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include <iostream>
#include <string>
#include <vector>

using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::vector;

bool isCharacter(char ch)
{
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
}

int ()
{
// 把单词存入vector,并忽略非字母
string str;
getline(cin, str);
const char *cp = str.c_str();
vector<string> raw;
string tmp = "";
while (*cp) {
if (isCharacter(*cp))
{
tmp += *cp++;
if (*cp != '