(完整word版)Thinking_in_C++_annotated_solution_guide(charpter_2)_第1頁
(完整word版)Thinking_in_C++_annotated_solution_guide(charpter_2)_第2頁
(完整word版)Thinking_in_C++_annotated_solution_guide(charpter_2)_第3頁
(完整word版)Thinking_in_C++_annotated_solution_guide(charpter_2)_第4頁
(完整word版)Thinking_in_C++_annotated_solution_guide(charpter_2)_第5頁
已閱讀5頁,還剩12頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領

文檔簡介

1、Chapter 22-1Modify Hello.cpp so that it prints out your name and age (or shoe size, or your dog' s age, if tmakes you feel better). Compile and run the program.Solution:The original Hello.cpp appeared in the text as follows:/ Saying Hello with C+#include <iostream> / Stream declarationsusi

2、ng namespacestd;int main() cout << "Hello, World! I am "<< 8 << " Today!" << endl;Here ' s my rewrite:S02:Hello2.cpp#include <iostream>using namespacestd;int main() cout << "Hello, World! I am Chuck Allison." << endl;cout &l

3、t;< "I have two dogs:" << endl;cout << "Sheba, who is " << 5 << ", and" << endl;cout << "Muffy, who is 8." << endl;cout << "(I feel much better!)" << endl;/* Output:Hello, World! I am Chuck All

4、ison.I have two dogs:Sheba, who is 5, andMuffy, who is 8.(I feel much better!)*/ /:I chose to have separate statements that send output tocout, but I could have printed everything in a single statement if I had wanted, like the example in the text does. Note that in the case of Sheba' s age, I p

5、rinted 5 as an integer, but for Muffy I included the numeral in the literal text. In this case it makes no difference, but when you print floating-point numbers that have decimals, you get 6 decimals by default. Bruce discusses later in the text how to control output of floating-point numbers.2-2Sta

6、rting with Stream2.cppand Numconv.cpp, create a program that asks for the radius of a circle and prints the area of that circle. You can just use the *' operatdo square the radius.Solution:The two programs mentioned above show how to do numeric input and output. The following solution to this ex

7、ercise likewise uses the left-shift and right-shift operators for input and output,respectively.:S02:Area.cpp-T echo run Area by hand!#include <iostream>using namespacestd;int main() constfloat pi = 3.141592654;cout << "Enter the radius:"float radius;cin >> radius;cout &l

8、t;< "The area is " << pi * radius * radius << endl;/* Sample Execution:c:>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

9、 a newline (via endl, say) after printing the prompt. That ' s becoinsis 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 so

10、urce file:S02:Words.cpp#include <iostream>#include <fstream>#include <string>using namespacestd;int main() ifstream f("Words.cpp");int nwords = 0;string word;while (f >> word)+nwords;cout << "Number of words = " << nwords << endl;/* Outpu

11、t:Number of words = 42*/ /:The <fstream> header defines classes for file IO, including ifstream, whose constructor takes a file name an argument. The expression f >> word extracts the next non-whitespace token from the file and returns the stream. When a stream appears in a boolean conte

12、xt, 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 you to map standard input or output to a file on the command line. If you rewrite Words.cpp to

13、 read from cin, then you can read any file you want, as the following illustrates.:S02:Words2.cpp/T < Area.cpp#include <iostream>#include <string>using namespacestd;int main() int nwords = 0;string word;while (cin >> word) +nwords;cout << "Number of words = " <

14、;< nwords << endl;/* Sample Execution: c:>words < Area.cppNumber of words = 41*/ /:The less-than symbol redirects standard input to come from the file Area.cpp, so that when you run the program, cin is hooked to that file. The greater-than symbol does the same for cout.2-4Create a pro

15、gram that counts the occurrence of a particular word in a file (use the string class operator ='' to find the word).Solution::S02:WordCount.cpp/ Counts the occurrences of a word#include <iostream>#include <fstream>#include <string>int main(int argc, char* argv) using namesp

16、acestd;/ Process command-line arguments:if (argc < 3) cerr << "usage: WordCount word filen"return -1;string word(argv1);ifstream file(argv2);/ Count occurrences:long wcount = 0;string token;while (file >> token)if (word = token)+wcount;/ Print result:cout << '"

17、;' << word << " " appeared "<< wcount << " timesn" /:This program uses the argc and argv arguments to main, which represent the argument count andarray of pointers to the arguments, respectively. If you don' t provide a word to search for and

18、a fileto search in, you get an error message and the program quits. The extraction operator for input streams skips whitespace when filling a string object, so token takes on each suc h " word " in thefile in succession. When run on its own text you get the following output:"word"

19、; appeared 3 timesmany functions, itNotice that in this example I chose to put the using directive in main, instead of at file scope. In these simple examples it really doesn matter where tyou put it, but in examples where you haves sometimes important to only put the directive inside the functions

20、that need it, to minimize the possibility of name clashes. Bruce discusses this in more detail in Chapter 4.2-5Change Fillvector.cpp so it prints the lines (backwards) from last to first.Solution:This modification to FillVector.cpp from the book requires only that you change the index to the vector

21、from i to v.size()-i-1.:S02:Fillvector.cpp/ Copy an entire file into a vector of string#include <string>#include <iostream>#include <fstream>#include <vector>using namespacestd;int main() vector<string> v;ifstream in("Fillvector.cpp");string line;while(getline

22、(in, line)v.push_back(line);/ Print backwards:int nlines = v.size();for(int i = 0; i < nlines; i+) int lineno = nlines-i-1;cout << lineno << ": " << vlineno << endl; /:2-6Change Fillvector.cpp so it concatenates all the elements in the vector into a single string

23、 before printing it out, but don' t try to add line numbering.Solution:Following the example of FillString.cpp , the program below appends each string in the vector to a string variable (lines), following each with a newline.:S02:Fillvector2.cpp/ Copy an entire file into a vector of string#inclu

24、de <string>#include <iostream>#include <fstream>#include <vector>using namespacestd;int main() vector<string> 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 &

25、lt; v.size(); i+)lines += vi + "n"cout << lines; /:2-7Display a file a line at a time, waiting for the user to press the“ Enter “ key after each linSolution:To make this program work as advertised, it' notiifopoWaeaCh display of a line with anewline character, otherwise the outpu

26、t will appear double-spaced.:S02:FileView.cpp/ Displays a file a line at a time#include <string> #include <iostream>#include <fstream>using namespacestd;int main() ifstream in("FileView.cpp");string line;while(getline(in, line) cout << line; / No endl!cin.get(); /:T

27、he call to cin.get( ) waits for you to press Enter and consumes a single character (the newline that results from pressing Enter).2-8Create a vector<float> and put 25 floating-point numbers into it using a for loop. Display the vector.Solution::S02:FloatVector.cpp/ Fills a vector of floats#inc

28、lude <iostream>#include <vector> using namespacestd;int main() / Fill vector:vector<float> v;for (int i = 0; i < 25; +i)v.push_back(i + 0.5);/ Displayfor (int i = 0; i < v.size(); +i) if (i > 0)cout << ''cout << vi;cout << endl;/* Output:0.5 1.5 2

29、.5 3.5 4.5 5.5 6.5 7.5 8.5 9.5 10.5 11.512.5 13.5 14.5 15.5 16.5 17.5 18.5 19.5 20.5 21.522.5 23.5 24.5*/ /:In this solution I decided to separate the numbers by spaces, to take up fewer lines in the output. I could have used 25 as the limit of the second for loop, but it ' s betterVeatsie:size(

30、 ), sincethat works no matter how many elements you process.2-9Create three vector<float> objects and fill the first two as in the previous exercise. Write a for loop that adds each corresponding element in the first two vectors and puts the result in the corresponding element of the third vec

31、tor. Display all three vectors.Solution::S02:FloatVector2.cpp/ Adds vectors#include <iostream>#include <vector>using namespacestd;int main() vector<float> v1, v2;for (int i = 0; i < 25; +i) v1.push_back(i);v2.push_back(25-i-1);/ Form sum:vector<float> v3;v3.push_back(v1i +

32、 v2i);/ Display:for (int i = 0; i < v1.size(); +i) cout «v1i « " + " « v2i« " = " « v3i « endl;/* Output:0 + 24 = 241 + 23 = 242 + 22 = 243 + 21 = 244 + 20 = 245 + 19 = 246 + 18 = 247 + 17 = 248 + 16 = 249 + 15 = 2410 + 14 = 2411 + 13 = 2412 + 12

33、= 2413 + 11 = 2414 + 10 = 2415 + 9 = 2416 + 8 = 2417 + 7 = 2418 + 6 = 2419 + 5 = 2420 + 4 = 2421 + 3 = 2422 + 2 = 2423 + 1 = 2424 + 0 = 24*/ /:It is crucial, of course, that you use push_back to fill v3. Mathematically we think of the operation as:v3i = v1i + v2i;/ wrong!but v3i does not exist unles

34、s you make space for it, which is exactly what push_back does. If you want to use the above expression instead, you can " size " the vectreswzh method, as follows:/ Form sum:vector<float> v3;v3.resize(v1.size(); / pre-allocate spacev3i = v1i + v2i;When you call resize on a vector, it

35、 truncates the sequence if the new size is smaller, or it appends “zeroes ” , if the number is larger, where" zero " means the appropriate value for the type ofcontained element. You can even resize vectors of strings and get empty strings added. Try it!2-10Create a vector<float> and put 25 numbers into it as in the previous exercises. Now square each number and p

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經權益所有人同意不得將文件中的內容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
  • 6. 下載文件中如有侵權或不適當內容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論