无法将sregex_iterator作为流传递给cout

时间:2014-11-22 14:32:27

标签: c++ regex c++11 iterator

我将以下文件保存为first.cpp

#include <iostream>
#include <string>
#include <regex>
using namespace std;

int main (){

    regex filenameRegex("[a-zA-Z_][a-zA-Z_0-9]*\\.[a-zA-Z0-9]+");

    string s2 = "Filenames are readme.txt and my.cmd.";

    sregex_iterator it(s2.begin(), s2.end(), filenameRegex);
    sregex_iterator it_end;

    while(it != it_end){
        cout << (*it) << endl;
        ++it;
    }

    return 0;
}

尝试使用命令g ++ first.cpp -o first -std = c ++ 11编译它会产生以下错误:

first.cpp: In function ‘int main()’:
first.cpp:16:15: error: cannot bind ‘std::ostream {aka std::basic_ostream<char>}’ lvalue to ‘std::basic_ostream<char>&&’
   cout << (*it) << endl;
               ^
In file included from /usr/include/c++/4.9/iostream:39:0,
                 from first.cpp:1:
/usr/include/c++/4.9/ostream:602:5: note: initializing argument 1 of ‘std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits<char>; _Tp = std::match_results<__gnu_cxx::__normal_iterator<const char*, std::basic_string<char> > >]’
     operator<<(basic_ostream<_CharT, _Traits>&& __os, const _Tp& __x)

我对此处发生的事情感到非常困惑。教程here指出,对sregex_iterator对象进行引用应该返回一个字符串。这不是真的吗?

1 个答案:

答案 0 :(得分:4)

std::sregex_iteratorstd::match_results<std::string::const_iterator>上的迭代器。要获得std::string,您需要使用str()方法:

while(it != it_end){
    std::cout << it->str() << '\n';
    ++it;
}

顺便说一句,请勿使用std::endl