不能将sregex_iterator作为流传递给 cout

Cannot pass sregex_iterator as a stream to cout

本文关键字:cout sregex iterator 不能      更新时间:2023-10-16

我将以下文件保存为第一个.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++ 编译它.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)

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

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

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

顺便说一句,不要使用std::endl.