gpt4 book ai didi

c++ - 无法将 sregex_iterator 作为流传递给 cout

转载 作者:行者123 更新时间:2023-11-27 23:01:35 25 4
gpt4 key购买 nike

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

最佳答案

A std::sregex_iteratorstd::match_results<std::string::const_iterator> 的迭代器.获得 std::string除此之外,您需要使用 str()方法:

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

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

关于c++ - 无法将 sregex_iterator 作为流传递给 cout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27078504/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com