logo CodeStepByStep logo

passports2

Write a function named passports2 (similar to the previous exercise, passports) that examines an input file full of passport data and returns the number of passports that are valid. Your function accepts a string parameter representing a file name as a parameter. A valid passport is one that contains all of the following required fields. The difference from the previous exercise is that the fields must match the following formats:

  • byr (Birth Year): four digits; at least 1920 and at most 2002.
  • iyr (Issue Year): four digits; at least 2010 and at most 2020.
  • eyr (Expiration Year): four digits; at least 2020 and at most 2030.
  • hgt (Height): a number followed by either cm or in. If cm, the number must be at least 150 and at most 193. If in, the number must be at least 59 and at most 76.
  • hcl (Hair Color): a # followed by exactly six characters 0-9 or a-f.
  • ecl (Eye Color): exactly one of: amb blu brn gry grn hzl oth.
  • pid (Passport ID): a nine-digit number, including leading zeroes.

A passport can also contain the following optional field:

  • cid (Country ID): ignored, missing or not.

Each passport in the input file is represented as a sequence of key:value pairs separated by spaces or newlines. Passports are separated by blank lines. For example, if the file named passports.txt contains the following text:

eyr:1972 cid:100
hcl:#18171d ecl:amb hgt:170 pid:186cm iyr:2018 byr:1926

pid:087499704 hgt:74in ecl:grn iyr:2012 eyr:2030 byr:1980
hcl:#623a2f

iyr:2019
hcl:#602927 eyr:1967 hgt:170cm
ecl:grn pid:012533040 byr:1946

eyr:2029 ecl:blu cid:129 byr:1989
iyr:2014 pid:896056539 hcl:#a97842 hgt:165cm

The first (eyr, hgt, pid) and third (eyr) passports are invalid; the second and fourth are valid. So the call of passports2("passwords.txt") should return 2.

You may assume that the file exists and is readable and that it follows the general format described above.

Function: Write a C++ function as described, not a complete program.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.