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.

5
  • Side note : You do not need if(static_cast<bool>(inFile)), use if(inFile) Commented Mar 14, 2016 at 20:48
  • You don't have to write if (static_cast<bool>(inFile)) {. InFile is contextually convertible to bool, so you can just write if (inFile) { Commented Mar 14, 2016 at 20:48
  • @DieterLücking lol, 10 seconds Commented Mar 14, 2016 at 20:49
  • Too much convenience (casts) ruins programming! Commented Mar 14, 2016 at 20:55
  • Further side note: you don't need if(static_cast<bool>(inFile)) or if(inFile). If the file didn't open, the call to getline will fail and lines will be empty. Commented Mar 14, 2016 at 23:27

2 Answers 2

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); } } 
Sign up to request clarification or add additional context in comments.

Comments

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; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.