0

So part of the assignment I am working on is I have to figure out if residents are old enough for retirement. I am getlining a string from a file and now I just need to find the year. Problem is, I have no clue how to go about this.

Here is the code so far

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

using namespace std;

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

And here is a sample string

Matthew Alan Aberegg 1963 452,627

I am thinking I need to use the find function to find a string with a space, four characters, then another space. But then Aland would get found.

Any help would be appreciated!

jchud13
  • 55
  • 6
  • Are you sure that `Matthew Alan Aberegg 1963 452,627` is in one single line? if is, then you can read one line and split it with whitespace. – Jiahao Cai Apr 05 '17 at 01:40

1 Answers1

1

Use the <regex> (C++11). The pattern

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

will match any four digit number. If you are only looking for recent year, the following pattern only matches nineteen hundreds and two thousands

\\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";
}
Henri Menke
  • 10,705
  • 1
  • 24
  • 42
  • 1
    You might want to add word boundary operators in there, or you will easily match 5-digit or longer numbers too. – paddy Apr 05 '17 at 01:49
  • This looks close to what I was looking for I will try this out thank you. – jchud13 Apr 05 '17 at 01:52
  • Hey I'm working on this code and I am getting an error that there is no viable overloaded operator for type smatch in the line if(regex_search(names,match,expr)){ return stoi(match[index]); } and I am not sure what that means – jchud13 Apr 06 '17 at 21:33