读取文件中的字符数和单词数

Reading number of characters and words in a file

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

/*
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

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

当您在第一个读取例程中到达文件末尾时 eofbit 标志设置为 true,以便能够在没有 closing/reopening 的情况下从同一流读取它,你需要重置它:

//...
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(){ /*...*/}