1

I'm trying to make a basic REPL that parse for special characters entered by a user. This post shows how to split on whitespace but I get this compiling error when I try to store the stringstream into the vector of strings.

repl.cpp: In function ‘int main(int, char**)’:
repl.cpp:52:25: error: range-based ‘for’ expression of type ‘std::__cxx11::basic_istringstream<char>’ has an ‘end’ member but not a ‘begin’
         for (string s : iss)
                         ^~~
repl.cpp:52:25: error: ‘std::ios_base::end’ cannot be used as a function
make: *** [repl.o] Error 1

Here is the full code below:

#include <cstdlib>                                                                                         
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <fstream>
#include <stdlib.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/stat.h>
using namespace std;

int main(int argc, char *argv[])
{
    size_t pos;
    int pipe = 0;
    int pid = 0;
    vector <size_t> positions;
    vector <string> arguments;
    do  
    {   
        cout << "repl$ ";
        getline(cin, cmd);

        pos = cmd.find( "|", 0); 
        while ( pos != string::npos )
        {   
            positions.push_back(pos);
            pos = cmd.find( "|", pos+1);
            pipe += 1;
            pid += 1;
        }   

        istringstream iss(cmd);

        while (iss >> cmd)
            arguments.push_back(cmd);  

        for (string s : iss)
            cout << s << endl;
  
    } while (cmd != "q");
    return EXIT_SUCCESS;
}             
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Char
  • 1,635
  • 7
  • 27
  • 38

1 Answers1

2

You need to use a std::istream_iterator<std::string> to read successive strings. Boost has a wrapper to create a pseudo-container representing the sequence of objects read from an istream; for example:

for (const auto& s : boost::range::istream_range<std::string>(iss))
    std::cout << s << '\n';

An alternative in this specific case would be to copy directly to an output iterator:

std::copy(std::istream_iterator<std::string>{iss},
          std::istream_iterator<std::string>{},
          std::ostream_iterator<std::string>{std::cout, '\n'});
Daniel Schepler
  • 3,043
  • 14
  • 20