Search
 
SCRIPT & CODE EXAMPLE
 

CPP

number of lines 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 :: max of a vector c++ 
Cpp :: how to make a list in c++ 
Cpp :: c++ console color 
Cpp :: flags for g++ compiler 
Cpp :: fstring from float c++ ue4 
Cpp :: opencv c++ image write 
Cpp :: return array from function c++ 
Cpp :: cpp initialize multidimensional vector 
Cpp :: c++ sieve of eratosthenes 
Cpp :: max_element c++ 
Cpp :: get window position 
Cpp :: c++ greatest common divisor 
Cpp :: c++ program transpose of matrix 
Cpp :: glew32.dll was not found 
Cpp :: binary representation c++ 
Cpp :: struct and pointer c++ 
Cpp :: stoi cpp 
Cpp :: c++ string to char array 
Cpp :: c++ array rev pointer 
Cpp :: string to upper c++ 
Cpp :: cannot jump from switch statement to this case label c++ 
Cpp :: reverse level order traversal 
Cpp :: memmove 
Cpp :: c++ get maximum value unsigned int 
Cpp :: c++ struct constructor 
Cpp :: c ifdef 
Cpp :: c++ erase remove 
Cpp :: check if element in dict c++ 
Cpp :: hello c++ 
Cpp :: count number of prime numbers in a given range in c 
ADD CONTENT
Topic
Content
Source link
Name
9+8 =