Search
 
SCRIPT & CODE EXAMPLE
 

CPP

number of words 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 :: search a word in cpp file 
Cpp :: c++ int main() 
Cpp :: c++ terminal color 
Cpp :: error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ 
Cpp :: file open cpp 
Cpp :: nth node from end of linked list 
Cpp :: find in string c++ 
Cpp :: c++ init multidimensional vector 
Cpp :: c++ segmented sieve 
Cpp :: c++ enum 
Cpp :: overload stream extract cpp 
Cpp :: what does the modularity mean in c++ 
Cpp :: c++ print string 
Cpp :: int to hex arduino 
Cpp :: c++ get character from string 
Cpp :: check if a string is palindrome cpp 
Cpp :: c++ vectors 
Cpp :: uses of gamma rays 
Cpp :: cpp loop through object 
Cpp :: how to split string in c++ 
Cpp :: case label in c++ 
Cpp :: reverse order binary tree in c++ 
Cpp :: how to convert ascii to char in cpp 
Cpp :: memory leak in cpp 
Cpp :: integer to char c++ 
Cpp :: c #define 
Cpp :: pure virtual function in c++ 
Cpp :: print counting in c++ 
Cpp :: cpp array init value 
Cpp :: c++ syntax 
ADD CONTENT
Topic
Content
Source link
Name
7+2 =