c++ - 计算文件输入的行数?

标签 c++

以下代码应该计算:从文本文件中读取的行、字符和单词。

输入文本文件:

This is a line.

This is another one.

所需的输出是:

Words: 8

Chars: 36

Lines: 2

但是,字数统计为 0,如果我更改它,则行数和字符数将为 0,并且字数统计是正确的。我得到这个:

Words: 0

Chars: 36

Lines: 2

这是我的代码:

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

using namespace std;


int main()
{
    ifstream inFile;
    string fileName;


    cout << "Please enter the file name " << endl;
    getline(cin,fileName);
    inFile.open(fileName.c_str());

    string line;
    string chars;
    int number_of_lines = 0;
    int number_of_chars = 0;

while( getline(inFile, line) )
    {
        number_of_lines++;
        number_of_chars += line.length();
    }

    string words;
    int number_of_words = 0;

while (inFile >> words)
    {
        number_of_words++;
    }

    cout << "Words: " << number_of_words <<"" << endl;
    cout << "Chars: " << number_of_chars <<"" << endl;
    cout << "Lines: " << number_of_lines <<"" << endl;

    return 0;
}

任何指导将不胜感激。

最佳答案

而且因为寻求答案的人通常不会阅读评论...

while( getline(inFile, line) ) 

读取整个文件。完成后,inFile 的读取位置设置为文件末尾,因此字数计数循环

while (inFile >> words)

从文件末尾开始读取,但什么也没找到。要使其正确执行,对代码进行的最小更改是使用 seekg在计算单词数之前倒带文件。

inFile.seekg (0, inFile.beg);
while (inFile >> words)

将读取位置定位到相对于文件开头的文件偏移量 0(由 inFile.beg 指定),然后读取文件以计算单词数。

虽然这有效,但它需要两次完整读取文件,这可能会非常慢。 crashmstr 在评论中建议并由 simplicis veritatis 实现的更好选项作为另一个答案需要读取一次文件来获取和计算行数,然后迭代 RAM 中的每一行来计算单词数。

总迭代次数相同,所有内容都必须一一计数,但从内存中的缓冲区读取优于从磁盘读取,因为速度快得多,访问和响应时间也高出几个数量级。

关于c++ - 计算文件输入的行数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32486171/

相关文章:

c# - 从 C# 调用 C++ 时出现 System.AccessViolationException

c++ - 为什么在 C++ 命名空间周围使用 extern "C"

C++ .txt 值到二维数组

java - 如何在 C++ 中编写具有多个数据字段的类 Java 枚举类?

c++ - 从类到整数类型的类型转换

c++ - QVector<int> 写入/调整大小性能

c++ - 如何为 select() 监控的每个套接字设置不同的超时时间?

c++ - 不能在 cpp 文件中包含 header

c++ - sizeof 和 alignof 有什么区别?

c++ - 如何在 QT 中制作模态 QProgressDialog?