lundi 19 septembre 2022

`getLine` function skipping the final, blank line in an input file

I want to find out the character length of each of the lines in a separate file, which is test.txt. test.txt contains two lines: the first contains hello, and the second is blank.

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main() {
    ifstream inFile;
    inFile.open("test.txt");
    string currline;

    while (getline(inFile, currline)) {
      cout << currline.length() << endl;
    }
}

When executing this program and inputting 'test.txt', I was expecting the output to be 5 0. However, the output was simply 5, which meant that the second line of test.txt was being ignored. How do I solve this issue without modifying the input file, or using a new modified file?

Aucun commentaire:

Enregistrer un commentaire