【问题标题】:I am trying to find the year in a string I have input from a file我正在尝试在我从文件输入的字符串中查找年份
【发布时间】:2017-04-05 01:29:48
【问题描述】:

所以我正在处理的部分任务是我必须弄清楚居民是否足够大到可以退休。我正在从文件中获取字符串,现在我只需要找到年份。问题是,我不知道该怎么做。

这是目前为止的代码

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

using namespace std;

int main(){
        ifstream oldretire;
        string names;  
        oldretire.open("oldretirement.txt");
        getline(oldretire, names);
        names find(
}    

这是一个示例字符串

马修·艾伦·阿贝雷格 1963 年 452,627

我想我需要使用 find 函数来查找一个带有空格、四个字符、然后是另一个空格的字符串。但后来奥兰会被发现。

任何帮助将不胜感激!

【问题讨论】:

  • 您确定Matthew Alan Aberegg 1963 452,627 在一行中吗?如果是,那么您可以读取一行并用空格分隔。

标签: c++ string file-io


【解决方案1】:

使用&lt;regex&gt; (C++11)。模式

\\b([0-9]{4})\\b

将匹配任何四位数字。如果您只查找最近的年份,则以下模式仅匹配 1902 和 2000

\\b(19|20)([0-9]{2})\\b

Demo

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

int find_year(std::string line, unsigned index = 0)
{
  std::smatch match;
  std::regex expr("\\b([0-9]{4})\\b"); // matches any four digit number

  if ( std::regex_search(line,match,expr) )
    return std::stoi(match[index]);
  else
    throw std::invalid_argument("No number matching a year found!");
}

int main()
{
  int year = find_year("Matthew Alan Aberegg 1963 452,627");
  std::cout << year << "\n";
}

【讨论】:

  • 您可能想在其中添加单词边界运算符,或者您也可以轻松匹配 5 位或更长的数字。
  • 这看起来很接近我正在寻找的东西我会试试这个谢谢。
  • 嘿,我正在处理此代码,我收到一个错误,即 if(regex_search(names,match,expr)){ return stoi(匹配[索引]); } 我不确定这意味着什么
猜你喜欢
  • 2023-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-01
  • 1970-01-01
  • 2020-07-04
相关资源
最近更新 更多