-
Notifications
You must be signed in to change notification settings - Fork 33
/
5.16.txt
40 lines (29 loc) · 1.16 KB
/
5.16.txt
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
Exercise 5.16: The while loop is particularly good at executing while some
condition holds; for example, when we need to read values until end-of-file.
The for loop is generally thought of as a step loop: An index steps through a
range of values in a collection. Write an idiomatic use of each loop and then
rewrite each using the other loop construct. If you could use only one loop,
which would you choose? Why?
Faisal Saadatmand
I'd choose the foor loop. I think in most cases its clearer and more compact.
// while: while some condition holds
std::string str;
while (std::cin >> str) {
cout << str << " "; // echo str
}
std::cout << '\n';
// for loop: index step
std::string line;
for (decltype(line.size()) i = 0; i != line.size() - 1; ++i)
line[i] = toupper(lin[i]); // capitalized the first letter of each line
// while loop: index step
std::string line;
decltype(line.size() i = 0;
while (i != line.szie() - 1) {
line[i] = toupper(lin[i]); // capitalized the first letter of each line
++i;
}
// for loop: while some condition holds
for (std::string str; std:cin >> str; )
std::cout << str << " "; // echo str
std::cout << '\n';