简体   繁体   中英

Reading a file and counting the number of lines c++

Hi there im struggling to read a file and count the lines in it. I pass this code and im getting 1 more line than my file has.


` ifstream fin;
    
        fin.open("car.txt");
        
    // num of cars counted
    numberOffCars = 0;
    while (fin.good()) //while i have not reached the eof
    {
        getline(fin, line);
        numberOffCars++;
    }
    cout<<numberOffCars<<endl;
    fin.close();``

Thanks

You can check if line is empty or not by simply using string::empty() . Here I have used std::ws to extract the leading whitespaces (if any).

Code:

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

int main() {
    std::ifstream fin("car.txt");
    if (not fin) {
        std::cerr << "car.txt not found in working directory!";
        return -1;
    }
    std::string str;
    int n = 0;
    while (fin >> std::ws and std::getline(fin, str))
        if(not str.empty())
            ++n;
    std::cout << n;
}

This will ignore the empty line(s) (the ones having just whitespaces). Moreover, the main problem with your code was that you were using getline when EOF was just about to be reached. You needed to check the condition after reading the input.

Here, in my code, first getline will be evaluated and then fin (returned by getline ) will be checked; it will tell us if last operation has succeeded or failed. In case EOF has been reached, it will fail, and consequently, the while loop will terminate.

Refer this thread for more information: Why is iostream::eof inside a loop condition (ie while (.stream.eof()) ) considered wrong? I would like to quote a comment from it: just because we haven't reached the EOF, doesn't mean the next read will succeed .

it's because your code knows "EOF" after it reads "EOF" and numberOffCars++; so result of numberOffCars is 1 more than what you expect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM