(2011.07.31)自学《C++ Primer Plus》时敲过的书上的代码!

来源:互联网 发布:剑网3女神脸数据 编辑:程序博客网 时间:2024/05/23 01:57

经过几个月的自学,最后在暑假自学完这本《C++ Primer Plus》啦!学到的东西跟细节很多,现在先不总结了,先把自己所敲过的代码放上来,重温一下。
下面这些是自学《C++ Primer Plus》时敲过的书上的代码:

//程序清单2.1 myfirst.cpp//myfirst.cpp--displays a message #include <iostream>//a PREPROCESSOR(预处理) directive(指令)int main()//function(函数) header(头){//start of function body (开始函数体)using namespace std;//make definitions(定义) visible(可见)cout << "Come up and C++ me some time.";//messagecout << endl;//start a new linecout << "You won't regret it!" << endl;return 0;//terminate(结束) main()}


//程序清单2.2 carrot.cpp//carrots.cpp(红萝卜) -- food processing(加工) program//uses(使用) and displays (显示) a variable(变量)#include <iostream>//a preprocessor directiveint main()//function header{//start of function bodyusing namespace std;//make definitions visibleint carrots;//declare(声明) an integer variablecarrots = 25;//assign(指派) a value to the variablecout << "I have";cout << carrots;cout << " carrots.";cout << endl;carrots = carrots - 1;//modify(修改) the variablecout << "Crunch, crunch. Now I have" << carrots << "carrots." << endl;return 0;//terminate main()}//end of function body


//程序清单2.3 getinfo.cpp//getinfo.cpp -- input and output#include <iostream>int main(){using namespace std;int carrots;cout << "How many carrots do you have?" << endl;cin >> carrots;cout << "Here are two more.";carrots = carrots + 2;//the next line concatenates outputcout << "Now you have " << carrots << " carrots." << endl;return 0;}


//程序清单2.4 sqrt.cpp//sqrt.cpp -- using the sqrt () function#include <iostream>#include <cmath> //or math.hint main(){using namespace std;double area;cout << " Enter the floor area, in square feet, of your home:";cin >> area;double side;side = sqrt(area);cout << "That's the equivalent of a square"<< " feet to the side." << endl;cout << "How fascinating!" << endl;return 0;}


//程序清单 2.5 ourfunc.cpp//ourfunc.cpp --defining your own function#include <iostream>void simon(int);//function prototype for simon()int main(){using namespace std;simon(3);//call the simon() functioncout << "Pick an integer:";int count;cin >> count;simon(count);//call it againcout << "Done!" << endl;return 0;}void simon(int n)//define the simon() function{using namespace std;cout << "Simon says touch your toes " << n << "times." << endl;//void functions don't need return statement}


//程序清单 2.6 convert.cpp#include <iostream>int stonetolb(int);//function prototypeint main(){using namespace std;int stone;cout << "Enter the weight in stone: ";cin >> stone;int pounds = stonetolb(stone);cout << stone << " stone = ";cout << pounds << " pounds." << endl;return 0;}int stonetolb(int sts){return 14 * sts;}

//程序清单 3.1 limits.cpp//limits.cpp -- some inteqer limits#include <iostream>// a propercessor directive#include <climits>// use limits.h for older systemsint main(){using namespace std;int n_int = INT_MAX;//initialize n_int to max int valueshort n_short = SHRT_MAX;//symbols defined in limits.h filelong n_long = LONG_MAX;//sizeof operatoryields size of type or of variablecout << "int is " << sizeof (int) << "bytes." << endl;cout << "short is " << sizeof n_short << " bytes." << endl;cout << "long is " << sizeof n_long << " bytes." << endl << endl;cout << "Maximum value:" << endl;cout << "int: " << n_int << endl;cout << "short: " << n_short << endl;cout << "long: " << n_long << endl << endl;cout << "minimum int value = " << INT_MIN << endl;cout << "Bits per byte = " << CHAR_BIT << endl;return 0;}


// 程序清单 3.3 hexoct.cpp// hexoct.cpp -- shows hex and octal constants#include <iostream>int main(){using namespace std;int chest = 42;// decimal integer constantint waist = 0x42;// hexadecimal integer constantint inseam = 042;// octal integer constantcout << "monsieur cuts a striking figure!\n";cout << "chest = " << chest << "\n";cout << "waist = " << waist << "\n";cout << "inseam = " << inseam << "\n";return 0;}


// 程序清单3.7 bondini.cpp// bondini.cpp -- using escape sequences#include <iostream>int main(){using namespace std;cout << "\aOPeration \"HyperHype\" is now activated!\n";cout << "Enter your agent code:________\b\b\b\b\b\b\b\b";long code;cin >> code;cout << "\aYou entered " << code << "...\n";cout << "\aCode verified! Proceed with Plan z3!\n";return 0;}//打印下线字符后,程序使用退格字符将光标退到第一个下划线处。


//程序清单4.1 arrayone.cpp//arrayone.cpp -- small arrays of integers#include <iostream>int main(){using namespace std;int yams[3];//creates array with three elementsyams[0] = 7;//assign value to first elementyams[1] = 8;yams[2] = 6;int yamcosts[3] = {20, 30, 5};//create,initialize array// NOTE: If your C++ complier or translator can't initizlize// this array, use static int yamcosts [3] instead of int yamcosts[3]cout << "Total yams = ";cout << yams[0] + yams[1] + yams [2] << endl;cout << "The package with " << yams[1] << " yams costs ";cout << yamcosts[1] << " cents per yam.\n";int total = yams[0] * yamcosts[0] + yams[1] * yamcosts[1];total = total + yams[2] * yamcosts[2];cout << "The total yam expense is " << total << " cents.\n";cout << "\nSize of yams array = " << sizeof yams;cout << " bytes. \n";cout << "Size of one element = " << sizeof yams[0];cout << " bytes.\n";return 0;}


// 程序清单 4.2 string.cpp// strings.cpp -- storing strings in an array#include <iostream>#include <string>int main(){using namespace std;const int Size = 15;char name1[Size];// empty arraychar name2[Size] = "C++owboy";// initialized array// NOTE: Some implementations may require the static keyword// to initialize the array name2cout << "Howdy! I'm " << name2;cout << "! What's your name?\n";cin >> name1;cout << "Well, " << name1 << ", your name has ";cout << strlen (name1) << " letters and is stored \n";cout << "in an array of " << sizeof (name1) << " bytes.\n";cout << "Your initial is  " << name1[0] << ".\n";name2[3] = '\0';// null charactercout << "Here are the first 3 characters of my name:";cout << name2 << "\n";return 0;}


// 程序清单4.4 instr2.cpp//instr2.cpp -- reading more than one word with getline#include <iostream>int main(){using namespace std;const int ArSize = 20;char name[ArSize];char dessert[ArSize];cout << "Enter your name:\n";cin.getline(name, ArSize);// reads through newlinecout << "Enter your favorites dessert: \n";cin.getline(dessert, ArSize);cout << "I have some delicious " << dessert;cout << " for you. " << name << ".\n";return 0;}


// 程序清单4.7 strtype1.cpp// strtype1.cpp -- using the C++ string class#include <iostream>#include <string>// make string class availableint main(){using namespace std;char charr1[20];// create an empty arraychar charr2[20] = "jaguar";// create an initialized arraystring str1;// create an empty string objectstring str2 = "jaguar";// create an intialized stringcout << "Enter a kind of feline: ";cin >> charr1;cout << "Enter another kind of feline: ";cin >> str1;// use cin for inputcout << "Here are some felines: \n";cout << charr1 << " " << charr2 << " "<< str1 << " " << str2// use cout for output<< endl;cout << "The third letter in " << charr2 << " is "<< charr2[2] << endl;cout << "The third letter in " << str2 << " is "<< str2[2] << endl;// use array notationreturn 0;}


// 程序清单4.8 strtype2.cpp// strtype1.cpp -- assigning, adding, and appending#include <iostream>#include <string>// make string class availableint main(){using namespace std;string s1 = "penguin";string s2, s3;cout << "You can assign one string object to another: s2 = s1\n";s2 = s1;cout << "s1: " << s1 << ", s2: " << s2 << endl;cout << "You can assign a C-style string to a string object.\n";cout << "s2 = \"buzzard\"\n";s2 = "buzzard";cout << "s2: " << s2 << endl;cout << "You can concatenate strings : s3 = s1 + s2\n";s3 = s1 + s2;cout << "s3: " << s3 << endl;cout << "You can append strings.\n";s1 += s2;cout << "s1 += s2 yields s1 = " << s1 << endl;s2 += " for a day ";cout << "s2 += \" for a day \" yields s2 = " << s2 << endl;return 0;}


// 程序清单4.9 strtype3.cpp// strtype3.cpp -- more string class features#include <iostream>#include <string>// make string class available// #include <cstring>// c=style string library int main(){using namespace std;char charr1[20];char charr2[20] = "jaguar";string str1;string str2 = "panther";// assignment for string objects and character arraysstr1 = str2;// copy str1 to str2strcpy(charr1, charr2);// copy charr2 to charr1// appending for string objects and character arraysstr1 += " paste";// add paste to end of str1strcat(charr1, " juice");// add juice to end of charr1// finding the length of a string object and a C-style stringint len1 = str1.size();// obtain length of str1int len2 = strlen(charr1);// obtain length of charr1cout << "The string " << str1 << " contains "<< len1 << " charracters.\n";cout << "The string " << charr1 << " contains "<< len2 << " characters.\n";return 0;}



// 程序清单 4.10 strtype4.cpp#include <iostream>#include <string>int main(){using namespace std;char charr[20];string str;cout << "Length of string in charr before input: "<< strlen(charr) << endl;cout << "Enter a line of text:\n";cin.getline(charr, 20);// indicate maximum lengthcout << "You entered: " << charr << endl;cout << "Enter another line of text:\n";getline(cin, str);// cin now an argument; no length specifiercout << "You entered:" << str << endl;cout << "length of string in charr after input: "<< strlen(charr) << endl;cout << "Length of string in str after input: "<< str.size() << endl;return 0;}    



// 程序清单 4.14 address.cpp// address.cpp -- using the & operator to find addresses#include <iostream>int main(){using namespace std;int donuts = 6;double cups = 4.5;cout << "donuts value = " << donuts;cout << " and donuts address = " << &donuts << endl;// NOTE: you may need to use unsigned ( &donuts) and unsigned (&cups)cout << "cups value = " << cups;cout << " and cups address = " << &cups << endl;return 0;}// 使用常规变量时,值是指定的量,而地址为派生量。// OPP强调的是在运行阶段(而不是编译阶段)进行决策



// 程序清单4.15 pointer.cpp// pointer.cpp -- our first pointer variable#include <iostream>int main(){using namespace std;int updates = 6;// declare a variableint * p_updates;// declare pointer to an intp_updates = &updates;// assign address of int to pointer// express values two wayscout << "Values: updates = " << &updates;cout << ", p_updates = " << *p_updates << endl;// express address two wayscout << "Addresses: &updates = " << &updates <<endl;cout << "Now updates = " << p_updates << endl;// use pointer to change value*p_updates = *p_updates +1;cout << "Now updates = " << updates << endl;return 0;}



// 程序清单 4.17 use_new.cpp// use_new.cpp -- using the new operator#include <iostream>int main(){using namespace std;int * pt = new int;// allocate space for an int*pt = 1001;// store a value therecout << "int ";cout << "value = " << *pt << ": location =  " << pt << endl;double * pd = new double;// allocate space for a double*pd = 10000001.0;//store a double therecout << "double ";    cout << "value = " << *pd << ": location = " << pd << endl;cout << "size of pt = " << sizeof (pt);cout << ": size of *pt = " << sizeof (*pt) << endl;cout << "size of pd = " << sizeof pd;cout << ": size of *pd = " << sizeof (*pd) << endl;return 0;}



// 程序清单 4.18 arraynew.cpp// arraynew.cpp -- using the new operator for arrays#include <iostream>int main(){using namespace std;double * p3 = new double [3];// space for 3 doublesp3[0] = 0.2;// treat p3 like an array namep3[1] = 0.5;p3[2] = 0.8;cout << "p3[1] is " << p3[1] << ".\n";p3 = p3 + 1;// increment the pointercout << "Now p3[0] is " << p3[0] << " and ";cout << "p3[1] is " << p3[1] << ".\n";p3 = p3 - 1;// point back to beginningdelete [] p3;return 0;}/**** 运行结果p3[1] is 0.5.Now p3[0] is 0.5 and p3[1] is 0.8.Press any key to continue****************************************/



// 程序清单 04.20 ptrstr.cpp// ptrstr.cpp -- using pointers to strings#include <iostream>#include <string>// declare strlen(),strcpy()int main(){using namespace std;char animal[20] = "bear";// animal holds bearconst char * bird = "wren";// bird holds address of stringchar * ps;// uninitializedcout << animal << " and ";// display bearcout << bird << "\n";// display bird// cout << ps << "\n";// may display garbage, may cause a crashcout << "Enter a kind of animal: ";cin >> animal;// ok if input < 20 chars// cin >> ps; Too horrible a blunder to try; ps doesn't// point to allocated spaceps = animal;// set ps to point to stringcout << ps << "s!\n";// ok,same as using animalcout << "Before using strcpy(): \n";cout << animal << " at " << (int * ) animal << endl;cout << ps << " at " << (int *) ps << endl;ps = new char[strlen (animal) +1];// get new storagestrcpy (ps, animal);//copy string to new storagecout << "After using strcpy(): \n";cout << animal << " at " << (int *) animal << endl;cout << ps << " at " << (int *) ps << endl;delete [] ps;return 0;}



// 程序清单_05.14_waiting.cpp// waiting.cpp -- using clock() in a time-delay loop#include <iostream>#include <ctime>// describes clock() function, clock_t typeint main(){using namespace std;cout << "Enter the delay time, in seconds: ";float secs;cin >> secs;clock_t delay = secs *CLOCKS_PER_SEC;// convert to clock tickscout << "starting\a\n";clock_t start = clock();while (clock() - start < delay)// wait until time elapses;    cout << "done \a\n";return 0;}// CLOCKS_PER_SEC  每秒钟系包含的系统时间单位数  将秒数乘以这个,即可得到以系统时间单位为单位的时间// clock() 为当前系统时间



// 程序清单 7.6 arrfun2.cpp// 将数组作为参数 // 将数组地址作为参数可以节省复制整个数组所需的时间和内存。// 如果数组很大,则使用拷贝的系统开销将非常大;// 程序不仅需要更多的计算机内存,还需要花费时间来复制大块的数据。// 另一方面,使用原始数据增加了破坏数据的风险。 // arrfu2.cpp -- functions with an array argument#include <iostream>const int ArSize = 8;int sum_arr(int arr[], int n);// use std:: instead of using directiveint main(){ int cookies[ArSize] = {1,2,4,8,16,32,64,128};// some systems require preceding int with static to enable array initialization   std::cout << cookies << " = array address, ";// some systems require a type cast: unsigned (cookies) enable array initialization   std::cout << sizeof cookies << " = sizeof cooikies\n";   int sum = sum_arr(cookies, ArSize);   std::cout << "Total cookies eaten: " << sum << std::endl;   sum = sum_arr(cookies, 3);// a lie   std::cout << "First three eaters ate " << sum << " cookies.\n";   sum = sum_arr(cookies + 4,4);            // another lie   std::cout << "Last four eaters ate " << sum << " cookies.\n";   while(2);   return 0;}// return the sum of an integer arrayint sum_arr (int arr[], int n){ int total = 0; std::cout << arr << " = arr,"; // some systems require a type cast: unsigned (arr)  std::cout << sizeof arr << " = sizeof arr\n"; for (int i = 0; i < n; i++) total = total + arr[i];    return total;}



// 程序清单 7.7 arrfun3.cpp -- array functions and const// 使用数组的调用的范例 1.填充数组 2.显示数组及用 const 保护数组 3.修改数组#include <iostream>const int Max = 5;// function prototypesint fill_array(double at[], int limit);void show_array(const double ar[], int n);  // don't change datavoid revalue(double r, double ar[], int n);int main(){ using namespace std;double properies[Max]; int size = fill_array(properies, Max);show_array(properies, size);cout << "Enter revaluation factor: ";double factor;cin >> factor;revalue(factor, properies, size);show_array(properies, size);cout << "Done.\n";return 0;}int fill_array(double ar[], int limit){ using namespace std; double temp; int i; for (i = 0; i < limit; i++) {   cout << "Enter value #" << (i+1) << ": ";   cin >> temp; if (!cin) // bad input(发现输入的数据不是int型)  {   cin.clear();while(cin.get()!= '\n')              continue;     cout << "Bad input; input process terminated, \n";break;  }  else if (temp <0)// signal to terminate    break;  ar[i] = temp;  }  return i;}   // the following function can use, but not alter. the array whose address is arvoid show_array(const double ar[], int n){  using namespace std;  for (int i = 0; i < n; i++)  {   cout << "Property #" << (i+1) << ": {1}quot;;   cout << ar[i] << endl;     }}// multiplies each element of ar[] by rvoid revalue (double r, double ar[], int n){  for (int i = 0; i < n; i++)   ar[i] *= r;}



// 程序清单_08.12_twotemps.cpp -- using overloaded template functions#include <iostream>template <class Any> // original templatevoid Swap(Any &a, Any &b);template <class Any> // new templatevoid Swap(Any *a, Any *b, int n);void Show(int a[]);const int Lim = 8;int main(){using namespace std;int i = 10, j = 20;cout << "i, j = " << i << ", " << j << ".\n";cout << "Using compiler-generated int swapper:\n";Swap(i, j);// matches original templatecout << "Now i, j = " << i << ", " << j << ".\n";int d1[Lim] = {0, 7, 0, 4, 1, 7, 7, 6};int d2[Lim] = {0, 6, 2, 0, 1, 9, 6, 9};cout << "Original arrays: \n";    Show (d1);Show (d2);Swap (d1, d2, Lim);// matches new templatecout << "Swapped arrays: \n";Show(d1);Show(d2);return 0;}template <class Any>void Swap (Any &a, Any &b)  {Any temp;temp = a;a = b;b = temp;}template<class Any>void Swap (Any a[], Any b[], int n){Any temp;for (int i = 0; i < n; i++){temp = a[i];a[i] = b[i];b[i] = temp;}}void Show(int a[]){using namespace std;cout << a[0] << a[1] << "/";cout << a[2] << a[3] << "/";for (int i = 4; i < Lim; i++){cout << a[i];}cout << endl;}



// stocks.cpp -- the whole program#include <iostream>#include <cstring>class Stock // class declaration{private:char company[30];int shares;double share_val;double total_val;void set_tot(){ total_val = shares * share_val;}public:void acquire(const char* co, int n, double pr);void buy(int num, double price);void sell(int num, double price);void update(double price);void show();};// note semicolon at the endvoid Stock::acquire(const char* co, int n, double pr){std::strncpy(company, co, 29);// truncate co to fit companycompany[29] = '\0';if (n < 0){std::cerr << "Number of shares can't be negative."<< company << " shares set to 0. \n";shares = 0;}elseshares = n;share_val = pr;set_tot();}void Stock::buy(int num, double price){if(num < 0){std::cerr << "Number of shares purchased can't be negative."<< "Transaction is aborted.\n";}else{shares += num;share_val = price;set_tot();}}void Stock::sell(int num, double price){using std::cerr;if (num < 0){cerr << "Number of shares sold can't be negative. "<< "Transaction is aborted.\n";}else if (num > shares){cerr << "You can't sell more than you have!"<< " Transaction is aborted. \n";}else{shares -= num;share_val - price;set_tot();}}void Stock::update(double price){share_val = price;set_tot();}void Stock::show(){using std::cout;using std::endl;cout << "Company: " << company<< " Shares: " << shares << endl<< " Share Price: {1}quot; << share_val<< " Total Worth: {1}quot; << total_val << endl;}int main(){using std::cout;using std::ios_base;Stock stock1;stock1.acquire("NanoSmart", 20, 12.50);cout.setf(ios_base::fixed);cout.precision(2);cout.setf(ios_base::showpoint);stock1.show();stock1.buy(15, 18.25);stock1.show();stock1.sell(400, 20.00);stock1.show();return 0;}



// 程序清单16.5_vect1.cpp -- introducing the vector template#include <iostream>#include <cstring>#include <vector>const int NUM = 5;int main(){using std::vector;using std::string;using std::cin;using std::cout;using std::endl;vector<int> ratings(NUM);vector<string> titles(NUM);cout << "You will do exactly as told. You will enter\n"<< NUM << " book titles and your ratings (0-10). \n";int i;for (i = 0; i < NUM; i++){cout << "Enter title #" << i + 1 << ": ";getline(cin, titles[i]);cout << "Enter your rating (0-10)";cin >> ratings[i];cin.get();}cout << "Thank you. You entered the following: \n"     << "Rating\tBook\n";for (i = 0; i < NUM; i++){cout << ratings[i] << "\t" << titles[i] << endl;}    cin.get();return 0;}



// 程序清单_16.6_vect2.cpp -- methods and iterators// 这次的注释是个人加上去的/*******************************************************************************让我们先看一下运行结果吧:Enter book title(quit to quit):The Cat who Knew VectorsEnter book rating:5Enter book title(quit to quit):Candid CaninesEnter book rating:7Enter book title(quit to quit):Warriors of WorkEnter book rating:4Enter book title(quit to quit):Quantum MannersEnter book rating:8Enter book title(quit to quit):quitThank you. You entered the follow:Rating  Book5       The Cat who Knew Vectors7       Candid Canines4       Warriors of Work8       Quantum Manners5       The Cat who Knew Vectors7       Candid Canines4       Warriors of Work8       Quantum MannersAfter erasure:5       The Cat who Knew Vectors8       Quantum MannersAfter insertion:7       Candid Canines5       The Cat who Knew Vectors8       Quantum MannersSwapping oldlist with books:5       The Cat who Knew Vectors7       Candid Canines4       Warriors of Work8       Quantum Manners*******************************************************************************/#include <iostream>#include <string>#include <vector>struct Review{std::string title;int rating;};bool FillReview(Review & rr);void ShowReview(const Review & rr);int main(){using std::cout;using std::vector;vector<Review> books;// 定义容器的方法Review temp;while(FillReview(temp))books.push_back(temp);// 容器将数据放到容器后的函数.push_back()int num = books.size();// 可用.size()测出容器的个数if(num > 0){cout << "Thank you. You entered the follow:\n"     << "Rating\tBook\n";for (int i = 0; i < num; i++){ShowReview(books[i]);}vector<Review>::iterator pr;// 定义迭代器,可将其看为容器的指针for (pr = books.begin(); pr != books.end(); pr++)// 迭代器可读取容器中的内容{ShowReview(*pr);}vector<Review> oldlist(books);// copy constructor usedif (num > 3){// remove 2 itemsbooks.erase(books.begin() + 1, books.begin() + 3);cout << "After erasure:\n";for (pr = books.begin(); pr != books.end(); pr++)// 开始与结束的位置{ShowReview(*pr);}// insert 1 itembooks.insert(books.begin(), oldlist.begin() + 1, oldlist.begin() + 2);// 将后面空间的内容插入到开始的参数的位置cout << "After insertion:\n";for (pr = books.begin(); pr != books.end(); pr++){ShowReview(*pr);}}books.swap(oldlist);// 将容器 oldlist 与 books 整个交换,可以理解成两个容器换了名字,不过值的地址也是有改变的。cout << "Swapping oldlist with books:\n";for (pr = books.begin(); pr != books.end(); pr++){ShowReview(*pr);}}else cout << "Nothing entered, nothing gained.\n";std::cin.get();return 0;}bool FillReview(Review & rr){std::cout << "Enter book title(quit to quit):";std::getline(std::cin, rr.title);if (rr.title == "quit")// 使用这个函数可以方便地退出程序,system call时。返回false{return false;}std::cout << "Enter book rating:";std::cin >> rr.rating;if (!std::cin)   return false;std::cin.get();return true;}void ShowReview (const Review &rr){std::cout << rr.rating << "\t" << rr.title << std::endl;}



// binary.cpp -- binary file I/O#include <iostream>// not required by most systems#include <fstream>#include <iomanip>#include <cstdlib>// (or stdlib.h)for exit()inline void eatline() { while(std::cin.get()!= '\n') continue; }struct planet{char name[20];// name of planetdouble population;// its populationdouble g;// its acceleration of gravity};const char * file = "planets.dat";int main(){using namespace std;planet pl;cout << fixed << right;// show initial contentsifstream fin;fin.open (file, ios_base::in | ios_base::binary);// binary file// NOTE: some systems don't accept the ios_base::binary modeif (fin.is_open()){cout << "Here are the current contents of the "<< file << " file: \n";while(fin.read((char *) &pl, sizeof pl)){cout << setw(20) << pl.name << ": "<< setprecision (0) << setw(12) << pl.population << setprecision (2) << setw(6) << pl.g << endl;}fin.close();}// add new data ofstream fout (file, ios_base::out | ios_base::app | ios_base::binary);//NOTE: some systems don't accept the ios::binary modeif(!fout.is_open()){cerr << "Can't open " << file << " file for output: \n";exit(EXIT_FAILURE);}cout << "Enter planet name(enter a blank line to quit): \n";cin.get(pl.name, 20);while(pl.name[0]!= '\0'){eatline();cout << "Enter planetary population: ";cin >> pl.population;cout << "enter planet's acceleration of gravity: ";cin >> pl.g;eatline();fout.write((char *)&pl, sizeof pl);cout << "Enter planet name (enter a blank line to quit):\n";}fout.close();// show revised filefin.clear();// not required for some implementations, but won't hurtfin.open (file, ios_base::in | ios_base::binary);if(fin.is_open()){cout << "Here are the new contents of the "<< file << " file: \n";while(fin.read((char*)&pl, sizeof pl)){cout << setw(20) << pl.name << ": "<< setprecision(0) << setw(12) << pl.population << setprecision(2) << setw (6) << pl.g << endl;}fin.close();}cout << "Done.\n";return 0;}