码迷,mamicode.com
首页 > 其他好文 > 详细

cpp primer 习题代码(更新)

时间:2016-07-02 21:24:05      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:

  1 3.1
  2  
  3 #include <iostream>
  4 using  std::cin;
  5 using std::cout;
  6 using std::endl;
  7 int main()
  8 {
  9     int base,exponent;
 10     long result=1;
 11     cout<<"Enter base and exponent:"<<endl;
 12     cin>>base>>exponent;
 13     if(exponent<0)
 14     {
 15         cout<<"Exponent can‘t be smaller than 0"<<endl;
 16         return -1;
 17     }
 18     else
 19     {
 20         for(int cnt=1;cnt<=exponent;++cnt)
 21         {
 22             result*=base;
 23         }
 24     }
 25     cout<<base<<" raised to the power of "<<exponent<<":"<<result<<endl;
 26     //cout << "Hello world!" << endl;
 27     return 0;
 28 }
 29 3.5
 30 //读入一行
 31 #include<iostream>
 32 using namespace std;
 33 int main()
 34 {
 35     string word;
 36     while(getline(cin,word))
 37     {
 38         cout<<word<<endl;
 39     }
 40     return 0;
 41 }
 42 //读入单词
 43 #include<iostream>
 44 using namespace std;
 45 int main()
 46 {
 47     string word;
 48     while(cin>>word)
 49     {
 50         cout<<word<<endl;
 51     }
 52     return 0;
 53 }
 54 3.8
 55 #include<iostream>
 56 using namespace std;
 57 int main()
 58 {
 59 string result_str,str;
 60 cin>>result_str;
 61 while(cin>>str)
 62     result_str=result_str+" "+str;
 63 cout<<result_str<<endl;
 64     return 0;
 65 }
 66 3.10
 67 #include<iostream>
 68 using namespace std;
 69 int main()
 70 {
 71 bool has_punct=false;
 72 string s,result_str;
 73 cout<<"Enter a String:"<<endl;
 74 getline(cin,s);
 75 for(string::size_type index=0;index!=s.size();++index)
 76 {
 77     if(ispunct(s[index]))
 78     {
 79         has_punct=true;
 80     }
 81     else
 82     {
 83         result_str+=s[index];
 84     }
 85 }
 86     if(has_punct)
 87         cout<<"Result:"<<result_str<<endl;
 88     else
 89     {
 90         cout<<"No punctuation character in the string"<<endl;
 91                 return -1;
 92     }
 93 return 0;
 94 }
 95 3.13
 96 #include<iostream>
 97 #include<vector>
 98 using namespace std;
 99 int main()
100 {
101     vector<int> ivec;
102     vector<int> sum;
103     int ival;
104     cout << "Enter numbers(Ctrl+Z to end):" << endl;
105     while(cin>>ival)
106             ivec.push_back(ival);
107             if(ivec.size()==0)
108             {
109                 cout<<"No elements"<<endl;
110             }
111     for (vector<int>::size_type index=0;index<ivec.size()-1;index=index+2)
112     {
113         if(ivec.size()%2!=0)
114         {
115             if(index<ivec.size()-1)
116             {
117                 sum.push_back(ivec[index]+ivec[index+1]);
118                 //sum.push_back(ivec[index]+ivec[ivec.size()-2-index]);
119             }
120         }
121         else
122         {
123              sum.push_back(ivec[index]+ivec[index+1]);
124                 // sum.push_back(ivec[index]+ivec[ivec.size()-1-index]);
125         }
126     }
127         if(ivec.size()%2!=0)
128         {
129             cout<<"Last element is not computed:"<<endl;
130         }
131         cout << "Sum of each pair of adjacent elements in the vector:"<<endl;
132         for (vector<int>::size_type index=0;index!=sum.size();++index)
133             {
134         cout<<sum[index]<<" ";
135             }
136         cout<<endl;
137 return 0;
138 }
139 3.14
140 #include<iostream>
141 #include<vector>
142 #include<string>
143 #include<cctype>
144 using namespace std;
145 int main()
146 {
147     cout<<"Enter some words:"<<endl;
148     vector <string> istr;
149     string iword;
150     while(cin>>iword)
151     istr.push_back(iword);
152     cout<<"After transformation:"<<endl;
153     for (vector<string>::size_type index=0;index<istr.size();++index)
154     {
155         for (string::size_type index2 = 0; index2 != istr[index].size(); ++index2)
156         {
157             istr[index][index2]=toupper(istr[index][index2]);
158         }
159         cout<<istr[index]<<"\t";
160         if((index%8==0)&&(index>0))
161         {
162             cout<<endl;
163         }
164     }
165     return 0;
166 }
167  
168 3.17
169 重做3.13
170 #include<iostream>
171 #include<vector>
172 using namespace std;
173 int main()
174 {
175     vector<int> ivec;
176     vector<int> sum;
177     int ival;
178     cout << "Enter numbers(Ctrl+Z to end):" << endl;
179     while(cin>>ival)
180     ivec.push_back(ival);
181     if(ivec.size()==0)
182     {
183         cout<<"No elements"<<endl;
184     }
185     for(vector<int>::iterator it=ivec.begin();it!=ivec.end()-1;it=it+2)
186     {
187         if(ivec.size()%2!=0)
188         {
189             if(it<ivec.end()-2)
190             {
191                 sum.push_back((*it)+*(it+1));
192             }
193         }
194         else
195         {
196              sum.push_back((*it)+*(it+1));
197         }
198     }
199         if(ivec.size()%2!=0)
200         {
201             cout<<"Last element is not computed:"<<endl;
202         }
203         cout << "Sum of each pair of adjacent elements in the vector:"<<endl;
204     for(vector<int>::iterator it2=sum.begin();it2!=sum.end();++it2)
205     {
206         cout<<*it2<<" ";
207     }
208         cout<<endl;
209 return 0;
210 }
211 重做3.14
212 #include<iostream>
213 #include<vector>
214 #include<string>
215 #include<cctype>
216 using namespace std;
217 int main()
218 {
219     cout<<"Enter some words:"<<endl;
220     vector <string> istr;
221     string iword;
222     while(cin>>iword)
223     istr.push_back(iword);
224     cout<<"After transformation:"<<endl;
225     for(vector<string>::iterator it=istr.begin();it!=istr.end();++it)
226     {
227         for(string::iterator it2=(*it).begin();it2!=(*it).end();++it2)
228         {
229             *it2=toupper(*it2);
230         }
231         cout<<*it<<"\t";
232         if((it-istr.begin())%8==0&&it>istr.begin())
233         {
234             cout<<endl;
235         }
236     }
237     return 0;
238 }
239  
240 3.18
241 #include<iostream>
242 #include<vector>
243 using namespace std;
244 int main()
245 {
246 vector<int> ivec(10,42);
247 for (vector<int>::iterator it=ivec.begin();it!=ivec.end();++it)
248 {
249      *it=*it*2;
250 }
251 for (vector<int>::iterator it=ivec.begin();it!=ivec.end();++it)
252 {
253      cout<<*it<<"\t";
254 }
255     return 0;
256 }
257  
258 4.15 解释指针和引用的主要区别。
259 使用引用(reference)和指针(pointer)都可间接访问另一个值,但它们之间存在两个重要区别:
260 (1)引用总是指向某个确定对象(事实上,引用就是该对象的别名),定义引用时没有进行初始化会出现编译错误;
261 (2) 赋值行为上存在差异:给引用赋值修改的是该引用所关联的对象的值,而不是使该引用与另一个对象关联。引用一经初始化,就始终指向同一个特定对象。给指针赋值修改的是指针对象本身,也就是使该指针指向另一对象,指针在不同时刻可指向不同的对象(只要保证类型匹配)。
262  
263 4.25 C风格字符串比较
264 #include<iostream>
265 #include<string>
266 #include<cstring>
267 using namespace std;
268 int main()
269 {
270     const int str_size=80;
271     char *str1,*str2;
272     str1=new char[str_size];
273     str2=new char[str_size];
274     if(str1==NULL||str2==NULL)
275     {
276         cout<<"No enough Memory"<<endl;
277         return -1;
278     }
279     cout<<"Enter two strings:"<<endl;
280     cin>>str1>>str2;
281     int result;
282     result=strcmp(str1,str2);
283     if(result>0)
284     cout << "\"" << str1 << "\"" << " is bigger than "<< "\"" << str2 << "\"" << endl;
285     else if (result < 0)
286     cout << "\"" << str2 << "\"" << " is bigger than "<< "\"" << str1 << "\"" << endl;
287     else
288     cout << "They are equal" << endl;
289     delete[] str1;
290     delete[] str2;
291     return 0;
292 }
293 4.29
294 (a) 这两段程序的功能是:执行一个循环次数为1000000 的循环,在该循环的循环体中:创建一个新字符串,将一个已存在的字符串复制给新字符串,然后比较两个字符串,最后释放新字符串。
295 #include<iostream>
296 #include<string>
297 #include<cstring>
298 using namespace std;
299 int main()
300 {
301      const char *pc = "a very long literal string";
302      const size_t len = strlen(pc +1);      // space to
303      for (size_t ix = 0; ix != 1000000; ++ix) {
304                  char *pc2 = new char[len + 1]; // allocate the space
305                  strcpy(pc2, pc);               // do the copy
306                  if (strcmp(pc2, pc))           // use the new string
307                      ;   // do nothing
308                  delete [] pc2;                 // free the memory
309           }
310          string str("a very long literal string");
311              // performance test on string allocation and copy
312      for (int ix = 0; ix != 1000000; ++ix) {
313                  string str2 = str; // do the copy, automatically allocated
314                  if (str != str2)           // use the new string
315                        ;  // do nothing
316           }
317     return 0;
318 }
319 4.30 字符串连接(Cstring style)
320 #include <cstring>
321 int main()
322 {
323 const char *cp1 = "Mary and Linda ";
324 const char *cp2 = "are firends.";
325 size_t len = strlen(cp1) + strlen(cp2);
326 char *result_str = new char[len+1];
327 strcpy(result_str, cp1);
328 strcat(result_str, cp2);
329 delete [] result_str;
330 return 0;
331 }
332 (C++ string style)
333 #include <string>
334 using namespace std;
335 int main()
336 {
337 const string str1("Mary and Linda ");
338 const string str2("are firends.");
339 string result_str;
340 result_str = str1;
341 result_str += str2;
342 return 0;
343 }
344 4.31 输入字符串到string,截断将string.c_str()copy到c风格字符串
345 #include <iostream>
346 #include <string>
347 #include <cstring>
348 using namespace std;
349 int main()
350 {
351     string in_str;// 用于读入字符串的string 对象
352     const size_t str_size = 10;
353     char result_str[str_size+1];// 读入字符串
354     cout << "Enter a string(<=" << str_size<< " characters):" << endl;
355     cin >> in_str;// 计算需复制的字符的数目
356     size_t len = strlen(in_str.c_str());
357     if (len > str_size)
358     {
359         len = str_size;
360         cout << "String is longer than " << str_size<< " characters and is stored only "
361         << str_size << " characters!" << endl;
362     }
363     // 复制len 个字符至字符数组result_str
364     strncpy(result_str, in_str.c_str(), len);
365     // 在末尾加上一个空字符(null 字符)
366     result_str[len+1] = \0;
367     return 0;
368 }
369 4.32&4.33
370 //int数组赋值给vector<int>
371 #include <iostream>
372 #include <vector>
373 using namespace std;
374 int main()
375 {
376     const size_t arr_size = 8;
377     int int_arr[arr_size];// 输入数组元素
378     cout << "Enter " << arr_size << " numbers:" << endl;
379     for (size_t ix = 0; ix != arr_size; ++ix)
380     cin >> int_arr[ix];// 用int 型数组初始化vector 对象
381     vector<int> ivec(int_arr, int_arr + arr_size);
382     return 0;
383 }
384 //vector<int>赋值给int数组
385 #include <iostream>
386 #include <vector>
387 using namespace std;
388 int main()
389 {
390     vector<int> ivec;
391     int ival;// 输入vector 元素
392     cout << "Enter numbers: (Ctrl+Z to end)" << endl;
393     while (cin >> ival)
394         ivec.push_back(ival);// 创建数组
395     int *parr = new int[ivec.size()];// 复制元素
396     size_t ix = 0;
397     for (vector<int>::iterator iter = ivec.begin();iter != ivec.end(); ++iter, ++ix)
398         parr[ix] = *iter;// 释放数组
399     delete [] parr;
400     return 0;
401 }
402 4.34&4.35
403 #include <iostream>
404 #include <string>
405 #include <cstring>
406 #include <vector>
407 using namespace std;
408 int main()
409 {
410     vector<string> ivec;
411     string str;
412     cout<<"Enter strings:"<<endl;
413     while(cin>>str)
414         ivec.push_back(str);
415     char **s2ptr=new char*[ivec.size()];
416     size_t ix=0;
417     for (vector<string>::iterator it=ivec.begin();it!=ivec.end();++it,++ix)
418     {
419         char *strptr=new char[(*it).size()+1];
420         strcpy(strptr,(*it).c_str());
421         s2ptr[ix]=strptr;
422       //  *s2ptr=strptr;
423       //  s2ptr=s2ptr+1;
424     }
425     cout << "Content of character arrays:" << endl;
426     for (ix =0; ix != ivec.size(); ++ix)
427     cout << *(s2ptr+ix) << endl;
428     // 释放各个字符数组
429     for (ix =0; ix != ivec.size(); ++ix)
430     delete [] s2ptr[ix];
431     // 释放字符指针数组
432     delete [] s2ptr;
433     return 0;
434 }
435  
436 8.3  流状态的查询和控制 ( 在保证程序的可靠性时经常遇到的问题 )
437  
438 C和C++的标准里从来没有定义过 fflush(stdin)。也许有人会说:“可是我用 fflush(stdin) 解决了这个问题,你怎么能说是错的呢?”的确,某些编译器(如VC6)支持用 fflush(stdin) 来清空输入缓冲,但是并非所有编译器都要支持这个功能(linux 下的 gcc 就不支持),因为标准中根本没有定义 fflush(stdin)。MSDN 文档里也清楚地写着fflush on input stream is an extension to the C standard(fflush 操作输入流是对 C 标准的扩充)。当然,如果你毫不在乎程序的移植性,用 fflush(stdin) 也没什么大问题。以下是 C99 对 fflush 函数的定义:
439  
440 /*
441 * 流状态的查询和控制
442 * 2010-3-26 wcdj
443 */
444 #include <iostream>
445 #include <stdexcept>
446 #include "stdio.h"
447 using namespace std;
448 void way1_cleario();
449 void way2_cleario();
450 int main()
451 {
452     int ival;
453     cout<<"Enter an interger:";
454     // read cin and test only for EOF;
455     // loop is executed even if there are other IO failures
456     while (cin>>ival, !cin.eof())
457     {
458         // input stream is corrupted; bail out
459         if (cin.bad())
460         {
461             throw runtime_error("IO stream corrupted");
462         }
463         // bad input
464         if (cin.fail())
465         {
466             cerr<<"bad data, try again/n";// warn the user
467             // reset the stream
468             //cin.clear(istream::failbit);// error, why?
469             cin.clear();// ok
470             way2_cleario();// eat excess bad stream
471             //way2_cleario();
472             continue;// get next input
473         }
474         // ok, to process ival
475         cout<<"ok, to process ival"<<endl;
476     }
477     return 0;
478 }
479 void way1_cleario()
480 {
481     int ival=0;
482     fflush(stdin); //不良代码,C++ codeblock下运行通过,下面代码输入要带空格
483     // 在C中,刷新缓冲区可以使用下面这样的代码
484     // 通过 while 循环把输入流中的余留数据“吃”掉
485     //一种移植性比较高的清空输入缓冲区办法
486  //   while((ival=getchar())!=‘/n‘&&ival!=EOF);
487   //  clearerr( stdin );
488 }
489 void way2_cleario()
490 {
491     cin.ignore(200, );// 输入的数据必须以空格分开,输入数据一定要有空格
492 }
493  
494 8.4 文件读写
495  
496 #include <fstream>
497 #include <iostream>
498 using namespace std;
499 const char * filename = "out.txt";
500 int main()
501 {
502     ofstream out;//写入文件处理
503     out.open("out.txt",ios_base::app);
504      if (out.is_open())
505     {
506          out << "This is a line.";
507          out << "This is another line.\n";
508          out.close();
509          out.clear();
510     }
511     char buffer0[256];
512     ifstream in("out.txt");//读取文件处理
513     if (! in.is_open())
514     {
515        cout << "Error opening file";
516        return 0;
517     }
518        while (!in.eof() )
519     {
520         in.getline (buffer0,100);
521         cout << buffer0 << endl;
522     }
523 }
524  
525 8.5. 字符串流
526  
527 #include <sstream>
528 #include <iostream>
529 using namespace std;
530 int main()
531 {
532     int val1=512,val2=1024;
533     ostringstream format_message;
534     format_message<<"val1:"<<val1<<"~"<<"val2:"<<val2<<"\n";
535     //format_message<<"val1:"<<val1<<"\n"<<"val2:"<<val2<<"\n";//这种输出,得到val1为0
536     istringstream input_istring(format_message.str());
537     cout <<format_message.str();
538     string dump;
539     input_istring >> dump >> val1 >> dump >> val2;
540     cout << val1 << " " << val2 << endl;  // prints 512 1024
541    return 0;
542 }
543  
544  

 

cpp primer 习题代码(更新)

标签:

原文地址:http://www.cnblogs.com/miki-52/p/5636017.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!