C + + Primer Fifth Edition exercise Answer chapter III

Source: Internet
Author: User

3.2 Write a program that reads a whole line at a time from the standard input, and then modifies the program to read one word at a time.
void readByLine (){    string line;?    while (getline (cin, line)) {        cout << line << endl;    }   }
void readByWord (){    string word;?    while (cin >> word) {        cout << word << endl;    }   }
3.3 Describes how the input and Getline functions of the string class handle whitespace characters, respectively.

The input operator automatically ignores whitespace (spaces, tabs, line breaks, and so on) before the string, from the first real character to the next blank space.
The Getline function saves whitespace in the string and reads the data until it encounters a newline character.

3.4 Writes a program, reads two strings, compares them for equality, and outputs the results. If not equal, the output of the larger string. Rewrite the above program, compare the input of the two string is equal length, if unequal, the output length of the larger string.
void compareString (){    string s1, s2;?    cin >> s1 >> s2;?    if (s1 == s2) {        cout << "equal" << endl;    } else if (s1 > s2){        cout << s1 << endl;    } else {        cout << s2 << endl;    }?}
void compareSize (){    string s1, s2;?    cin >> s1 >> s2;    if (s1.size() == s2.size()) {        cout << "equal" << endl;    } else if (s1.size() > s2.size()) {        cout << s1 << endl;    } else {        cout << s2 << endl;    }}
3.5 Write a program that reads multiple strings from the standard input and joins them together, outputting a large string of connections. Then modify the program and separate the input strings with a space.
void linkString (){    string word;    string sum;?    while (getline (cin, word)) {?        sum += word;        cout << sum << endl;    }   }
void spliteString (){    string word;    string sum;?    while (getline(cin, word)) {        sum += (word + " ");        cout << sum << endl;    }}
3.6 Write a program that uses the range for statement to replace all characters in a string with X.
void test306 (){    string str("hello world!");    int len = str.size();?   //  for (int i = 0; i < len; i++) {  //      str[i] = ‘x‘;  //  }      for (auto &c : str) {          c = ‘X‘;      }   ?    cout << str << endl;}
3.7 What happens when you set the type of the loop control variable to char on the previous program?

Answer: It is also possible to set to char, because each element is of type char.

3.8 Rewrite the first question with a while loop and a for loop respectively, which is the better way?

Answer: With the common for loop implementation, such as the 3.6 code in the comment section, while implementation is similar to the first to know the length of the string. In contrast, the range for statement is a little more concise.

3.9 What is the function of the following program? Is it legal? If it's not legal, why?
 string s; cout << s[0] << endl;

Answer: Illegal, using an out-of-range subscript throws unpredictable results, and it is inferred that using subscript to access an empty string can also cause unpredictable results.

3.10 Write the program, read into a string containing punctuation marks, remove punctuation after the output string remaining parts.
void test310 (){      const string str = "0123&*sjaa,.?70!";      string result;?      for (auto c : str) {        // if ((c>=‘0‘ && c<=‘9‘) || (c>=‘a‘ && c<=‘z‘) || (c>=‘A‘ && c<=‘Z‘)) {     if (!ispunct(c)) { //ispunct函数,如果c为标点符号时为真。              result += c;          }         }   ?      cout << result << endl;  }
3.11 is the following range for statement legal? If legal, what is the type of C?
const string s = "Keep out!";for (auto &c : s) { /*. . . */ }

Illegal, when setting a reference to an auto type, the top-level const in the initial value remains, and the type of C is const string&. Therefore, if you want to change the value of C in the For loop, the statement is not valid.

3.12 are the following vector objects defined correctly?
vector<vector> ivec; //合法,创建类型为vector的对象。 vector svec = ivec; //不合法,svec是string类型,而ivec是vector类型。 vectorsvec(10, "null"); //合法,创建10个string类型的元素,每个都被初始化为null
3.13 How many elements are in each of the following vector objects? What is the value of each?
(a)vector<int> v1;                         //不包含元素(b)vector<int> v2(10);                   //包含10个元素,每个都初始化为0(c)vector<int> v3(10, 42);             // 包含10个元素,每个都初始化为42(d)vector<int> v4{10};                  // 包含1个元素,值为10 (e)vector<int> v5{10, 42};            // 包含2个元素,值分别是10和42(f)vector<string> v6{10};              // 10个默认初始化的元素,初始化为空(g)vector<string> v7{10, "hi"};     // 10个值为hi的元素
3.14 Write a program that reads a set of integers in CIN and stores them in a vector object.
void test314 ()  {      vector<int> ivec;      int num;      while (cin >> num) {          ivec.push_back(num);      }      vector<int>::iterator iter;      for (iter = ivec.begin(); iter != ivec.end(); iter ++) {          cout << *iter << " ";      }      cout << endl;  }

CTRL + D End Input

3.15 rewrite the program, read into the string.
void test315 ()  {      vector<string> svec;      string str;      while (cin >> str) {          svec.push_back(str);      }?      vector<string>::iterator iter;?      for (iter = svec.begin(); iter != svec.end(); iter ++) {          cout << *iter << " ";      }      cout << endl;  }
3.16 Write a program that will output the capacity and value of the vector object in 13 questions. Verify that the previous answer is correct.
void test316 ()  {      vector<int> v1; //不包含元素      vector<int> v2(10); //包含10个元素,每个都初始化为0      vector<int> v3(10, 42); // 包含10个元素,每个都初始化为42      vector<int> v4{10}; // 包含1个元素,值为10      vector<int> v5{10, 42}; // 包含2个元素,值分别是10和42      vector<string> v6{10}; // 10个默认初始化的元素,初始化为空      vector<string> v7{10, "hi"}; // 10个值为hi的元素?      vector<int>::iterator iter;      for (iter = v3.begin(); iter != v3.end(); iter++) {          cout << *iter << " ";      }     }

3.17 read a set of words from CIN and put them into a vector object, then try to capitalize all the words. The result of the output change, with each word occupying one line.

void test317 ()  {      string word;      vector<string> svec;?      while (cin >> word) {           svec.push_back(word);      }   ?      for (auto &str : svec) {          for (auto &c : str) {              c = toupper(c);          }         }   ?      for (auto i : svec) {          cout << i << endl;      }     }
3.18 is the following procedure legal? How do I change it?
vector<int> ivec;ivec[0] = 42;

Illegal, Ivec is empty, contains no elements, and cannot be accessed by subscript. Should be changed to Ivec.push_back (42);

3.19 If you want to define a vector element with 10 elements, all element values are 42, please list three different ways, which is better?
vector<int> ivec1(10, 42);vector<int> ivec2 (ivec1);vector<int> ivec3 {42, 42, 42, 42, 42, 42, 42, 42, 42, 42};

The first kind is better and more concise. You can also use the For loop to assign values, but it's tedious.

3.20 read into a set of integers and put them into a vector object, each pair of adjacent integers and output, rewrite the program, this time the first and last output of the sum, and then output the second and the penultimate sum, and so on.
void test318 ()  {         int num;      vector<int> ivec;      vector<int> sum;?      while (cin >> num) {          ivec.push_back(num);      }??      for (vector<int>::size_type i = 0; i < ivec.size(); i+=2) {          sum.push_back(ivec[i]+ivec[i+1]);      }?      for (auto &s : sum) {          cout << s << " ";      }      cout << endl;}
void test319 ()  {      int num;      vector<int> ivec;      vector<int> sum;?      while (cin >> num) {          ivec.push_back(num);      }   ?      vector<int>::size_type len = ivec.size();      int temp;// 如果有奇数个数字,则最中间的数会与自己相加一遍,未排除这种情况      for (vector<int>::size_type i = 0; i < (len+1)/2; i++) {          temp = ivec[i]+ivec[len-i-1];          cout << "i = " << i << " temp = " << temp << endl;          sum.push_back(temp);      }   ?      for (auto &s : sum) {          cout << s << " ";      }         cout << endl;}
3.21 Please use the iterator to do 3.16 questions.

The iterator has been used, not to repeat it.

3.23 Create a Vector object with 10 integers, using an iterator to change the value of all elements to twice times the previous one.
void test323()  {      vector<int> integer(10, 2); ?      for (auto& iter : integer) {          iter *= 2;      }   ?      for (auto it : integer) {          cout << it << " ";      }         cout << endl; }
3.24 use the iterator to do 3.20 questions.

The above answer is done with an iterator.

3.25 score segments are divided into grades, using iterators.

void test325 () {     vector<unsigned> scores (0),      unsigned grade;   &nbs P  int i = 0;      int n = 0;      auto iter = Scores.begin ();      while (I < 5) {         cin >> grade,         & Nbsp;if (Grade >) {             cout << "wrong grade!" << Endl; &nb Sp            continue;        }            n = GRADE/10;      //Scores[n] + +;          iter = iter + N;         (*iter) + +;          i++;          iter = Scores.begin ();    }  ?      cout << "scores is:";      for (auto iter:scores) {         cout << ITER << "";            cout << Endl; } ?

C + + Primer Fifth Edition exercise answer chapter III

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.