【问题标题】:Cannot pass sregex_iterator as a stream to cout无法将 sregex_iterator 作为流传递给 cout
【发布时间】:2015-01-20 14:39:38
【问题描述】:

我将以下文件另存为 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 对象应该返回一个字符串。这不是真的吗?

【问题讨论】:

  • 教程错了。

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


【解决方案1】:

std::sregex_iteratorstd::match_results&lt;std::string::const_iterator&gt; 的迭代器。要从中获取std::string,您需要使用str() 方法:

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

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

【讨论】:

  • 谢谢!您能否提供有关错误消息的更多信息?看起来它是在说 *它返回类型 std::basic_ostream&&
  • @HarryBraviner:错误消息只是指出std::match_results&lt;...&gt; 没有输出运算符。它以一种有点奇怪的方式声明的原因是存在一个模板化重载,它采用任意第二个参数和一个 std::basic_ostream&lt;...&gt;&amp;&amp; 作为第一个参数。
猜你喜欢
  • 1970-01-01
  • 2018-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-18
  • 1970-01-01
相关资源
最近更新 更多