版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領
文檔簡介
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. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年度網絡安全防護服務合同2篇
- 2025版果園租賃與農業(yè)觀光旅游合作協(xié)議2篇
- 二零二五年度屋頂防水隔熱彩鋼瓦安裝服務合同樣本2篇
- 2025年度綠色建筑PPP項目合作協(xié)議2篇
- 二零二五年度洗衣店加盟商合同范本3篇
- 腳手架安全監(jiān)理細則模版(2篇)
- 統(tǒng)計行政指導工作方案模版(2篇)
- 低壓配電室操作規(guī)程(2篇)
- 二零二五年度新型環(huán)保建筑材料采購銷售合同范本3篇
- 二零二五年度昆明公租房電子合同租賃合同簽訂與租賃雙方責任劃分3篇
- 第47屆世界技能大賽江蘇省選拔賽計算機軟件測試項目技術工作文件
- 2023年湖北省公務員錄用考試《行測》答案解析
- M200a電路分析(電源、藍牙、FM)
- 2024-2030年全球及中國洞察引擎行業(yè)市場現(xiàn)狀供需分析及市場深度研究發(fā)展前景及規(guī)劃可行性分析研究報告
- 建筑工程施工圖設計文件審查辦法
- 置業(yè)顧問考核方案
- 吉林市2024-2025學年度高三第一次模擬測試 (一模)數(shù)學試卷(含答案解析)
- 自考《英語二》高等教育自學考試試題與參考答案(2024年)
- 應急物資智能調配系統(tǒng)解決方案
- 2025年公務員考試時政專項測驗100題及答案
- 《春秋》導讀學習通超星期末考試答案章節(jié)答案2024年
評論
0/150
提交評論