首页 > 解决方案 > 读取文件中的字符数和单词数

问题描述

我试图编写一个程序来找出文件中的字符数和单词数:

/*
Write C++ program to count:
Number of characters in a file
Number of words in a file
Number of lines in a file
*/
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
    int countOfCharacters = 0;
    int countOfWords = 0;
    ifstream ins;
    ins.open("hello.txt", ios::in);
    char c;
    while (ins.get(c))
    {
        countOfCharacters += 1;
    }
    cout << "Total Number of characters is " << countOfCharacters << endl;
    ins.seekg(0,ios::beg);
    while(ins.get(c))
    {   cout << "Character is " << c <<endl;
        if (c==' ' || c=='.' || c=='\n'){
        countOfWords+=1;
        }
    }
    cout << "Total number of words in the file is " <<countOfWords <<endl;
    ins.close();
return 0;
}

对于以下输入:

Hi Hello Girik Garg

我得到的输出为:

Total Number of characters is 19
Total number of words in the file is 0

有人能告诉我为什么我没有得到正确的字数吗?

标签: c++fileiofstream

解决方案


当您在第一个读取例程中到达文件末尾时,eofbit标志设置为true,为了能够在不关闭/重新打开它的情况下从同一流中读取,您需要重置它:

//...
ins.clear(); //<--
ins.seekg(0, ios::beg);
//...

话虽如此,您可以按照@YSC 的建议在同一个周期中进行这两个计数:

while (ins.get(c))
{        
    countOfCharacters += 1;
    if (c == ' ' || c == '.' || c == '\n')
    {
        countOfWords += 1;
    } 
}

请注意,如果该行不以\n(或'.'/ ' ')结尾,则不计算最后一个单词,您应该验证流是否确实打开:

if(ins.is_open(){ /*...*/}

推荐阅读