Q:

Rewrite the previous program to store each word in a separate element

0

Rewrite the previous program to store each word in a separate element.

All Answers

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

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

std::vector<std::string> read(const std::string &filename) {
  std::ifstream in(filename);
  std::vector<std::string> vs;
  if (in) {
    for (std::string s; in >> s; )
      vs.push_back(s);
  } else {
    std::cerr << "Fail to open file: " << filename << std::endl;
  }
  return vs;
}

int main() {
  std::string filename;
  std::cin >> filename;
  auto vs = read(filename);
  for (decltype(vs.size()) i = 0; i != vs.size(); ++i)
    std::cout << i + 1 << "\t: " << vs[i] << 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