How to find the longest word in a text file in C++
Hi guys, today we will see how to find the longest word in a text file in C++.
Before we start with this topic, I would like to tell you the methods to read a file.
Methods To Read A File
You can learn about file handling from this website: file handling. I am hereby extending the topic.
We can read a text file in three ways:
- Character By Character
char ch; while(!f.eof()) { f.get(ch); }
- Word By Word
char ch[25]; while(!f.eof()) { f>>ch; }
- Line By Line
char ch[100]; while(!f.eof()) { f.getline(ch,100); }
Find The Longest Word
So after discussing the methods to read a file, let’s move ahead to the solution.
In this problem, we will assume that we have a text file named as file.txt containing the following data:
apple banana cherry pineapple watermelon
So to find the longest word, we will read this text file word by word. After reading a word, we will store that word in a variable ‘ch’. Initially, we will declare an integer variable ‘max’ and assign it with a value equal to zero.
Now, we will calculate the size of each word using the strlen() function and check whether it is greater than the value stored in ‘max’ or not. If the value comes out to be greater than the value of ‘max’ then, we will update the value of ‘max’ with this new value and copy that word in another variable ‘ch1’ using strcpy() function.
This process continues until every word of the text file gets checked.
In the end, we will get the longest word in the variable ‘ch1’ and its length in variable ‘max’.
Code:
ifstream f; f.open("file.txt"); char ch[100],ch1[100]; int max=0; while(!f.eof()) { f>>ch; if(max<strlen(ch)) { max=strlen(ch); strcpy(ch1,ch); } } f.close(); cout<<ch1;
In this code, we are displaying the longest word. So, its output will be
watermelon
We can also display the length of the longest word by printing the value of the variable ‘max’.
Leave a Reply