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

void reverse_words(const std::string &file) {
    std::ifstream inFile { file };
    std::vector<std::string> lines;
    if(static_cast<bool>(inFile)) {
        std::string line;
        while(std::getline(inFile, line, '\n')) {
                lines.push_back(line);
        }

    std::vector<std::string> reverse_line;
    std::string word;
    for(auto line: lines) {
        while(std::getline(line, word, ' '))
            reverse_line.push_back(word);

    }

    }
}

int main(int argc, char ** argv) {
    if(argc == 2) {
        reverse_words(argv[1]);
    }
}

In the last for loop of my program I would like to read in a word from a line, the line is a string so this does not match the getline() function definition. How can I cast the line to a stringstream so that I can use it for reading just like a file ?

Please ignore the logic of the program at the moment, it is not complete, my question is C++ specific.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • Side note : You do not need `if(static_cast(inFile))`, use `if(inFile)` –  Mar 14 '16 at 20:48
  • You don't have to write `if (static_cast(inFile)) {`. `InFile` is contextually convertible to `bool`, so you can just write `if (inFile) {` – Barry Mar 14 '16 at 20:48
  • @DieterLücking lol, 10 seconds – Barry Mar 14 '16 at 20:49
  • Too much convenience (casts) ruins programming! –  Mar 14 '16 at 20:55
  • Further side note: you don't need `if(static_cast(inFile))` or `if(inFile)`. If the file didn't open, the call to `getline` will fail and `lines` will be empty. – Pete Becker Mar 14 '16 at 23:27

2 Answers2

2

You just have to construct an istringstream:

for(auto const& line: lines) {
    std::istringstream iss{line};  // <-------
    while(std::getline(iss, word, ' ')) {
        reverse_line.push_back(word);
    }
}    
Barry
  • 286,269
  • 29
  • 621
  • 977
2
std::string s("hello world");
std::istringstream ss(s);
std::string s1, s2;
ss >> s1 >> s2;
std::cout << s1 << std::endl;
std::cout << s2 << std::endl;
Richard Hodges
  • 68,278
  • 7
  • 90
  • 142