Q:

The program in this section defined its istringstream object inside the outer while loop

0

The program in this section defined its istringstream object inside the outer while loop. What changes would you need to make if record were defined outside that loop? Rewrite the program, moving the definition of record outside the while, and see whether you thought of all the changes that are needed.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

#include <string>
#include <vector>
#include <iostream>
#include <sstream>
using std::vector;
using std::string;
using std::cin;
using std::istringstream;
using std::getline;

struct PersonInfo {
  string name;
  vector<string> phones;
};

int main() {
  string line, word;
  vector<PersonInfo> people;
  istringstream record;
  while (getline(cin, line)) {
    PersonInfo info;
    record.clear();  // Note this line.
    // The stream must be reset because after reading the first line, the
    // stream's state is end-of-file, and calling `str(someString)` member
    // function will not reset the stream's state. Thus, `clear()` must be
    // called explicitly.
    // However, the `open()` member funtion of `fstream` will automatically
    // reset the stream's state if it succeeds.
    record.str(line);
    record >> info.name;
    while (record >> word)
      info.phones.push_back(word);
    people.push_back(info);
  }

  for (const auto &e : people) {
    std::cout << e.name << ": ";
    for (const auto &p : e.phones)
      std::cout << p << " ";
    std::cout << std::endl;
  }

  return 0;
}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now