Search
 
SCRIPT & CODE EXAMPLE
 

CPP

number of characters in c++ files

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    char ch;
    int words = 0, characters=0 , lines=0;

    ifstream file("myfile.txt");
    file.seekg(0,ios::end); // points to the end of file
    int length = file.tellg(); // returns the end of file's index , if its 0 then the file is empty

    if(!file) // checks the existence of file
    {
        cout<< "file was not found ";
    }

    if (length == 0)
    {
        cout << "file is empty
 ";
        cout << "words = " <<words <<endl
             << "line = " <<lines <<endl
             << "characters = " << characters <<endl;
    }

    else
    file.seekg(0,ios::beg); // pointer set to beginning as it was pointing to the end
    {
        while (file)
        {
            file.get(ch);
            if (ch == ' ')
            {
                words ++; 
            }

            if (ch == '
')
            {
                lines ++;
            }

            characters ++;
        }
        cout<< "words = " <<words+1 <<endl // they are incremented to one because they were initialized to 0
            << "line = "  <<lines+1 <<endl
            << "characters = " << characters+1 <<endl;

        return 0;

        /*
        there might be a question that , what if there was no words or letters or line,
        the program will always give 1
        the answer is a no character case occurs if the file is empty
        since the program already checks for that case, its ggs
        */
    }
}
Comment

PREVIOUS NEXT
Code Example
Cpp :: how to check if a number is prime c++ 
Cpp :: read text from file c++ 
Cpp :: c++ add object to array 
Cpp :: c++ get full line of input 
Cpp :: how to make copy constructor in c++ 
Cpp :: c++ typeid 
Cpp :: how to pass function as a parameter in c++ 
Cpp :: cpp create multidimensional vector 
Cpp :: sieve of eratosthenes algorithm in c++ 
Cpp :: C++ std::string find and replace 
Cpp :: overload stream insert cpp 
Cpp :: char ascii c++ 
Cpp :: matrix transpose in c++ 
Cpp :: the code execution cannot proceed because glew32.dll was not found 
Cpp :: check if char in string c++ 
Cpp :: how to get the type of a variable in c++ 
Cpp :: tolower funciton in cpp 
Cpp :: how to find the sum of a vector c++ 
Cpp :: c++ print 3d cube 
Cpp :: loop through array c++ 
Cpp :: c++ function default argument 
Cpp :: cpp create lambda with recursion 
Cpp :: cpp vs c# 
Cpp :: pragma cpp 
Cpp :: integer range in c++ 
Cpp :: c pre-processor instructions 
Cpp :: how to change colour image to grey in opencv c++ 
Cpp :: how to use custom array in c++ 
Cpp :: set width qpushbutton 
Cpp :: find a number in vector c++ 
ADD CONTENT
Topic
Content
Source link
Name
7+2 =