Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to count the characters in a text file

Tags:

c++

visual-c++

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;
}
like image 617
user836910 Avatar asked Oct 28 '25 21:10

user836910


2 Answers

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

while( getline ( inMyStream, line ) )
{
    cout << line << endl;
    c += line.length();
}
like image 134
BeemerGuy Avatar answered Oct 31 '25 10:10

BeemerGuy


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;
like image 45
sbabbi Avatar answered Oct 31 '25 10:10

sbabbi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!