MVS C++ error : string subscript out of range -


I want to solve the following:

There was a text file "pesel.txt" given , Which includes 150 national identities, each line has a national identity, which is an 11-digit number. The first two digits from left to the last year, in which a person was born, the next two digits fixed month and the next two scheduled days.

To reduce: <0 p> points 0-1 = year points 2-3 = month digits 4-5 = day digits 6-11 = set another, which is not important here < / P>

I need to read the file, check how many people were born in December. I'm trying to do this in the following way:

  • After reading each row
  • On each line, I check whether the third letter in the string is equal to 1 And if the fourth letter is equal to 2, then yes, I increase the pay scale, which is my match for those born in December, and the next loop is executed

    Here is the code:

      int _tmain (int argc, _TCHAR * argv []) {ifstream ("C: \\ Cuba \\ Study and Boat \" Matra XDDD \ INFA \\ 1 \\ Dane_PR \\ pesel.txt "); String Line; Int Jan Jan = 0; if (! File.is_open () } {Cout & lt; & lt; "File can not be read." & Lt; & lt; end ;; and} while {file.good ()} {getline (file, line); if (line [2] == '1' & amp; amp; Line [3] == '2') {Born January Dec. ++; // 0-1 years, 2-3 months, 4-5 days}} cout & lt; Lt; "The amount of people born in December:" & lt;  < / Pre> 

    The problem is that I have the following And I do not know why ..

    while File.good () is incorrect - getline will still fail You have read the last line of the file, process it, file.good () right now It is also true, then you try to read another row and the getline fails.

    You also need to check that the line is too long before you reach line [n] or you get an error right away.

      int argtc, _TCHAR * argv []) {ifstream file ("C: \\ Cuba \\ study and boat \\ metura XDDD \\ INFA \\ 1 \\ Dane_PR \\ pesel.txt "); String line; Int Jan = 0; If (! File.is_open ()) {cout & lt; & Lt; "The file can not be read." & Lt; & Lt; Andal; } Else {while (getline (file, line)} // When we have read a line (line.size ()> gt; = 4) {// and the row is too long (line [2] == ' 1 '& amp; Line [3] ==' 2 ') {// We check birth conditions December ++; // 0-1 years, 2-3 months, 4-5 days}}} cout & lt; & Lt; "The amount of people born in December:" & lt; & Lt; BornInDecember & lt; & Lt; Endl; File.close (); } System ("pause"); Return 0; }    

Comments