【发布时间】: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.