C++ istringstream range-based for loop has no begin member
我正在尝试做一个基本的repl,解析用户输入的特殊字符。这篇文章展示了如何在空白处进行拆分,但是当我试图将字符串流存储到字符串向量中时,我会得到这个编译错误。
1 2 3 4 5 6 | 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 |
以下是完整代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | #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> arguements; 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) arguements.push_back(cmd); for (string s : iss) cout << s << endl; } while (cmd !="q"); return EXIT_SUCCESS; } |
您需要使用
1 2 3 | for (const auto& s : boost::range::istream_range<std::string>(iss)) std::cout << s << ' '; |
在这种特定情况下,另一种选择是直接复制到输出迭代器:
1 2 3 4 | std::copy(std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{}, std::ostream_iterator<std::string>{std::cout, ' '}); |