【问题标题】:No viable overloaded operator for type smatch类型匹配没有可行的重载运算符
【发布时间】:2017-04-06 21:56:59
【问题描述】:

我正在使用正则表达式尝试在一行代码(4 个整数)中查找年份。我在这一行编译时出错,如果他们找到四个字符,我想将它们作为整数返回。

if(regex_search(names,match,expr)){
    return stoi(match[index]);
}

索引似乎是问题所在,这是一个无符号索引,用作函数查找年份的参数。感谢您的帮助,如果您需要更多信息,请告诉我。

这里是所有代码

#include <iostream>
#include <fstream>
#include <string>
#include <regex>

using namespace std;

int find_year(string& names, unsigned index = 0);

int main(){
    ifstream oldretire;
    string names;
    oldretire.open("oldretirement.txt");
    getline(oldretire, names);
    int year = find_year(names);
    cout << year;
}

int find_year(string& names){
    smatch match;
    regex expr("[0-9]{4}");

    if(regex_search(names,match,expr)){
        return stoi(match[index]);
    }
    else
        cout << "No matching arguement";
}

【问题讨论】:

  • 贴出所有代码。
  • 好的,我都贴出来了
  • 如果只需要匹配值,为什么要使用index?试试stoi(match.str())
  • find_year() 函数定义的签名与函数声明的签名不匹配。
  • 您对regex_search 的参数顺序错误。 names, expr, match.

标签: c++ regex string


【解决方案1】:

您的代码中有两个问题:

  • 两个find_year 签名不匹配。 (这个导致编译错误)
  • 如果找不到匹配项,则缺少 return 语句。

修正版:

#include <iostream>
#include <string>
#include <regex>

using namespace std;

int find_year(string& names, unsigned index = 0);

int main(){
    string names = "foo bar barbar1829foofoo";
    int year = find_year(names);
    cout << year;
    return 0;
}

int find_year(string& names, unsigned index){
    smatch match;
    regex expr("[0-9]{4}");

    if(regex_search(names,match,expr)){
        return stoi(match[index]);
    }
    else
        cout << "No matching arguement";
    return -1;
}

提示:如果下次找不​​到问题所在,最好使用更严格的编译选项编译程序,例如 -Wall -pedantic -Wextra

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-20
    • 2021-11-03
    • 1970-01-01
    • 2015-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多