#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.
if(static_cast<bool>(inFile)), useif(inFile)if (static_cast<bool>(inFile)) {.InFileis contextually convertible tobool, so you can just writeif (inFile) {if(static_cast<bool>(inFile))orif(inFile). If the file didn't open, the call togetlinewill fail andlineswill be empty.