1、 Viewing Hints Book Home Page Free Newsletter Seminars Seminars on CD ROM Consulting Annotated Solution GuideRevision 1.0for Thinking in C+, 2nd edition, Volume 1by Chuck Allison2001 MindView, Inc. All Rights Reserved. Previous Chapter Table of Contents Next Chapter Chapter 22-1Modify Hello.cpp so t
2、hat it prints out your name and age (or shoe size, or your dogs age, if that makes you feel better). Compile and run the program.Solution:The original Hello.cpp appeared in the text as follows:/ Saying Hello with C+#include / Stream declarationsusing namespace std;int main() cout using namespace std
3、;int main() cout using namespace std;int main() const float pi = 3.141592654;cout radius;cout areaEnter the radius: 12The area is 452.389*/ /:The const keyword declares that the float variable pi will not be changed during the execution of the program. Note that it is not necessary to insert a newli
4、ne (via endl, say) after printing the prompt. Thats because cin is tied to cout, which means that cout always gets flushed right before you read from cin.2-3Create a program that opens a file and counts the whitespace-separated words in that file.Solution:The first version opens its own source file:
5、/: S02:Words.cpp#include #include #include using namespace std;int main() ifstream f(“Words.cpp“);int nwords = 0;string word;while (f word)+nwords;cout header defines classes for file IO, including ifstream, whose constructor takes a file name an argument. The expression f word extracts the next non
6、-whitespace token from the file and returns the stream. When a stream appears in a boolean context, such as the while statement above, it evaluates to true until end-of-file reached or an error occurs.It turns out that on many operating systems you can take advantage of i/o redirection, which allows
7、 you to map standard input or output to a file on the command line. If you rewrite Words.cpp to read from cin, then you can read any file you want, as the following illustrates./: S02:Words2.cpp/T #include using namespace std;int main() int nwords = 0;string word;while (cin word) +nwords;cout words
8、#include #include int main(int argc, char* argv) using namespace std;/ Process command-line arguments:if (argc token)if (word = token)+wcount;/ Print result:cout #include #include #include using namespace std;int main() vector v;ifstream in(“Fillvector.cpp“);string line;while(getline(in, line)v.push
9、_back(line);/ Print backwards:int nlines = v.size();for(int i = 0; i #include #include #include using namespace std;int main() vector v;ifstream in(“Fillvector2.cpp“);string line;while(getline(in, line)v.push_back(line);/ Put lines into a single string:string lines;for(int i = 0; i v.size(); i+)lines += vi + “n“;cout lines; /: