In this C++ program we are counting the number of words, lines and the total size of a text file in bytes. I have used a text file “story.txt”. Make sure you already created this file and have some text in it. Place this file in the same directory where your source code file is present. I have used proper comments in the program to make it easy to understand. If you are still facing any problem then you can ask your questions in comment section.
Also Read: C++ Program to Count no. of alphabates, digits and spaces present in a file STORY.TXT
#include<iostream.h> #include<fstream.h> int main() { ifstream fin("story.txt"); //opening text file int line=1,word=1,size; //will not count first word and last line so initial value is 1 char ch; fin.seekg(0,ios::end); //bring file pointer position to end of file size=fin.tellg(); //count number of bytes till current postion for file pointer fin.seekg(0,ios::beg); //bring position of file pointer to begining of file while(fin) { fin.get(ch); if(ch==' '||ch=='n') word++; if(ch=='n') line++; } cout<<"Lines="<<line<<"nWords="<<word<<"nSize="<<size<<"n"; fin.close(); //closing file return 0; }
What’s the use of line no. 12,15,19??? U are simply putting the pointer to beg. Only..
i was edit this program for counting average word size
#include
#include
using namespace std;
int main()
{
ifstream fin(“file.txt”); ///opening text file
int line=1,word=1,size = 1; ///will not count first word and last line so initial value is 1
char ch;
fin.seekg(0,ios::end); ///bring file pointer position to end of file
size=fin.tellg(); ///count number of bytes till current position for file pointer
fin.seekg(0,ios::beg); ///bring position of file pointer to beginning of file
while(fin)
{
fin.get(ch);
if(ch==’ ‘||ch==’\n’)
word++;
if(ch==’\n’)
line++;
}
cout<<"Lines="<<line<<" "<<"nWords="<<word<<" "<<"nSize="<<(size/word)<<" "<<"n";
fin.close(); //closing file
return 0;
}
Sir
I am new to programming. I am learning basics from your site. They really help me a lot. Could you please tell me what “story.txt” mean? Is it the file name? Should that particular file be open? can i do this with any file from my computer? does it require path directory?
You can use any file. If the source code file and text file are in the same directory then no need to provide path.
how about if you wanted to present in a column all the individual words and in the next column it displays the number of characters in each individual word?
On here:
#include
#include
What does the h means?
h stands for header file, its an extension.
its #include
what if there are multiple spaces between 2 words ??????????????????????????????
Hi,
I want calculate only length text from line in file. Can you please me. Actually i have used strlen() but it calculating spaces from line.
hi
i want to calculate length of each line in the text file could u plz help me