Q:

Write a program to store each line from a file in a vector<string>. Now use an istringstream to read each element from the vector a word at a time

0

Write a program to store each line from a file in a vector<string>. Now use an istringstream to read each element from the vector a word at a time.

All Answers

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

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

int main() {
  std::vector<std::string> vs;
  std::string filename;
  std::cin >> filename;
  std::ifstream in(filename);
  if (!in) {
    std::cerr << "Fail to open file: " << filename << std::endl;
    return -1;
  }
  for (std::string line; std::getline(in, line); vs.push_back(line)) {}
  for (const auto &e : vs) {
    std::istringstream iss(e);
    for (std::string word; iss >> word; std::cout << word << 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