简体   繁体   English

读取文件并统计行数 c++

[英]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.我传递了这段代码,我得到的代码比我的文件多了 1 行。


` 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() .您可以通过简单地使用string::empty()来检查行是否为空。 Here I have used std::ws to extract the leading whitespaces (if any).在这里,我使用std::ws来提取前导空格(如果有的话)。

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.此外,您的代码的主要问题是您在即将到达EOF时使用getline 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;在这里,在我的代码中,将首先评估getline然后检查fin (由getline返回); 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.如果达到EOF ,它将失败,因此while循环将终止。

Refer this thread for more information: Why is iostream::eof inside a loop condition (ie while (.stream.eof()) ) considered wrong?有关详细信息,请参阅此线程: 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 .我想引用其中的一条评论Just because we haven't reached the EOF, doesn't mean the next read will success

it's because your code knows "EOF" after it reads "EOF" and numberOffCars++;这是因为您的代码在读取“EOF”和 numberOffCars++ 后知道“EOF”; so result of numberOffCars is 1 more than what you expect.所以 numberOffCars 的结果比你预期的多 1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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