从文件输入计数行?

时间:2015-09-09 17:49:12

标签: 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;
}

非常感谢任何指导。

2 个答案:

答案 0 :(得分:2)

因为答案寻求者经常不读评论......

while( getline(inFile, line) ) 

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

while (inFile >> words)

开始在文件末尾读取并找不到任何内容。对代码进行正确执行的最小变化是在计算单词之前使用seekg重绕文件。

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

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

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

这具有相同的总迭代次数,所有内容都必须逐个计算,但是从内存缓冲区读取比从磁盘读取更好,因为它显着更快,数量级,访问和响应时间。

答案 1 :(得分:1)

以下是一种可能的实施方案(未经测试)用作基准:

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;
}