user836910
user836910

Reputation: 484

how to count the characters in a text file

im trying to count the characters inside a text file in c++, this is what i have so far, for some reason im getting 4. even thou i have 123456 characters in it. if i increase or decrease the characters i still get 4, please help and thanks in advance

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

using namespace std;

const char FileName[] = "text.txt";

int main () 
{
string line;
ifstream inMyStream (FileName); 
int c;

if (inMyStream.is_open()) 
{

     while(  getline (inMyStream, line)){

             cout<<line<<endl;
              c++;
  }
    }
    inMyStream.close(); 

system("pause");
   return 0;
}

Upvotes: 4

Views: 64324

Answers (8)

Andreas
Andreas

Reputation: 36

C++ provides you with a simple set of functions you can use to retrieve the size of stream segment.

In your case, we want to find the file end, which can be done by using fstream::seekg, and providing the fstream::end.

note that fstream is not implementing the end iterator overload, this is it's own end constant

When we've seeked towards the end of the file, we want to get the position of the stream pointer, using tellg (also known as the character count in our case).

But we're not done yet. We need to also set the stream pointer to its original position, otherwise we'll be reading from the end of the file. Something we don't want to do.

So lets call fstream::seekg again, but this time set the position to the begining of the file using fstream::beg

std::ifstream stream(filepath);

//Seek to end of opened file
stream.seekg(0, stream.end); 
int size = stream.tellg();

//reset file pointer to the beginning of the file
stream.seekg(0, stream.beg);

Upvotes: 0

Martin Melichar
Martin Melichar

Reputation: 1156

This works for sure, it is designed to read character by character.

It could be easily put into a class and you may apply function for every char, so you may check for '\n', ' ' and so on. Just have some members in your class, where they can be saved, so you may only return 0 and use methods to get what exactly you want.

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

unsigned long int count(std::string string)
{
    char c;
    unsigned long int cc = 0;

    std::ifstream FILE;
    FILE.open(string);
    if (!FILE.fail())
    {
        while (1)
        {
            FILE.get(c);
            if (FILE.eof()) break;
            cc++; //or apply a function to work with this char..eg: analyze(c);
        }
        FILE.close();
    }
    else
    {
        std::cout << "Counter: Failed to open file: " << string << std::endl;
    }

    return cc;
};

int main()
{
    std::cout << count("C:/test/ovecky.txt") << std::endl;

    for (;;);

    return 0;
}

Upvotes: 0

Brenden
Brenden

Reputation: 27

this is how i would approach the problem:

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

using namespace std;


int main () 
{
string line;
int sum=0;
ifstream inData ;
inData.open("countletters.txt");

while(!inData.eof())
{
getline(inData,line);

    int numofChars= line.length();
    for (unsigned int n = 0; n<line.length();n++)
    { 
    if (line.at(n) == ' ')
    {
    numofChars--;
    }
    }
sum=numofChars+sum;
}
cout << "Number of characters: "<< sum << endl;
    return 0 ;
}

Upvotes: 1

Subbu
Subbu

Reputation: 2101

I found out this simple method , hope this helps

while(1)
    {
        if(txtFile.peek() == -1)
            break;
        c = txtFile.get();
        if(c != txtFile.eof())
                    noOfChars++;
    }

Upvotes: 0

Richard J. Ross III
Richard J. Ross III

Reputation: 55563

Just use good old C FILE pointers:

int fileLen(std::string fileName)
{
    FILE *f = fopen(fileName.c_str(), "rb");

    if (f ==  NULL || ferror(f))
    {
        if (f)
            fclose(f);

        return -1;
    }

    fseek(f, 0, SEEK_END);
    int len = fell(f);

    fclose(f);

    return len;
}

Upvotes: 1

shengy
shengy

Reputation: 9749

First of all, you have to init a local var, this means: int c = 0; instead of int c;

I think the old and easy to understand way is to use the get() function till the end char EOF

    char current_char;
    if (inMyStream.is_open()) 
        {

            while(inMyStream.get(current_char)){

                if(current_char == EOF)
                {
                    break;
                }
                c++;
            }
        }

Then c will be the count of the characters

Upvotes: 1

sbabbi
sbabbi

Reputation: 11181

There are probably hundreds of ways to do that. I believe the most efficient is:

    inMyStream.seekg(0,std::ios_base::end);
    std::ios_base::streampos end_pos = inMyStream.tellg();

    return end_pos;

Upvotes: 7

BeemerGuy
BeemerGuy

Reputation: 8269

You're counting the lines.
You should count the characters. change it to:

while( getline ( inMyStream, line ) )
{
    cout << line << endl;
    c += line.length();
}

Upvotes: 7

Related Questions