从文件输入中计算行数

Counting lines from a file input?

本文关键字:计算 文件 输入      更新时间:2023-10-16

下面的代码应该计数:从文本文件中读取的行,字符和单词。

输入文本文件:

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中对每行进行迭代以计数单词数。

这具有相同的总迭代次数,所有内容都必须逐一计数,但是从内存中的缓冲区读取比从磁盘读取更可取,因为从内存中读取要快得多,数量级,访问和响应时间

这里有一个可能的实现(未测试)用作基准:

int main(){
// print prompt message and read input
cout << "Please enter the file name " << endl;
string fileName;
getline(cin,fileName);
// create an input stream and attach it to the file to read
ifstream inFile;
inFile.open(fileName.c_str());
// define counters
string line;
string chars;
int number_of_lines = 0;
int number_of_chars = 0;
vector<string> all_words;
do{
    getline(inFile, line);
    // count lines
    number_of_lines++;
    // count words
    // separates the line into individual words, uses white space as separator
    stringstream ss(line);
    string word;
    while(ss >> word){
        all_words.push_back(word);
    }
}while(!inFile.eof())
// count chars
// length of each word
for (int i = 0; i < all_words.size(); ++i){
    number_of_chars += all_words[i].length(); 
}
// print result
cout << "Words: " << all_words.size() <<"" << endl;
cout << "Chars: " << number_of_chars <<"" << endl;
cout << "Lines: " << number_of_lines <<"" << endl;
return 0;
}