




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
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. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 广东潮州卫生健康职业学院《环境生态工程与设计》2023-2024学年第二学期期末试卷
- 山西省运城市运康中学2025年初三1月份阶段模拟测试化学试题试卷含解析
- 2025年安徽省利辛县重点达标名校初三下学期期中英语试题文试卷含答案
- 山东中医药高等专科学校《数字化建筑设计概论》2023-2024学年第二学期期末试卷
- 山东肥城市泰西中学2025届高三第二次校模拟考试生物试题含解析
- 内蒙古美术职业学院《医疗器械管理及法规》2023-2024学年第一学期期末试卷
- 2025年重庆市北岸区初三第一次调研考试(一模)物理试题含解析
- 重庆健康职业学院《信息检索竞赛》2023-2024学年第一学期期末试卷
- 苏州工艺美术职业技术学院《小学生识字写字教学》2023-2024学年第二学期期末试卷
- 北京舞蹈学院《就业指导-职业生涯规划》2023-2024学年第二学期期末试卷
- 110kV立塔架线安全施工方案
- 完形填空-2025年安徽中考英语总复习专项训练(含解析)
- 20180510医疗机构门急诊医院感染管理规范
- DL∕T 5210.2-2018 电力建设施工质量验收规程 第2部分:锅炉机组
- 2024北京海淀区初二(下)期末物理及答案
- 基层医疗卫生机构6S管理标准1-1-5
- 2018容器支座第1部分:鞍式支座
- 重点关爱学生帮扶活动记录表
- 江苏省苏州市2023-2024学年四年级下学期期中综合测试数学试卷(苏教版)
- 2024-2029年中国生鲜吸水垫行业市场现状分析及竞争格局与投资发展研究报告
- 华大新高考联盟2024届高三3月教学质量测评语文试题及答案
评论
0/150
提交评论