Harry Braviner
Harry Braviner

Reputation: 677

Cannot pass sregex_iterator as a stream to cout

I save the following file as 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;
}

Attempting to compile it with the command g++ first.cpp -o first -std=c++11 produces the following error:

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)

I am very confused about what is going on here. The tutorial here states that deferenceing an sregex_iterator object should return a string. Is this not true?

Upvotes: 0

Views: 367

Answers (1)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153830

A std::sregex_iterator is an iterator over std::match_results<std::string::const_iterator>. To get a std::string out of it, you'd need to use the str() method:

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

BTW, don't use std::endl.

Upvotes: 4

Related Questions