Click here to Skip to main content
15,901,426 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I counted the length of the largest and shortest word, but how to count the length without spaces and punctuation.
My text file:
One One
Two
Three
Three..G
OneOne
Five
Four
Nn
New New New

What I have tried:

My code:
C++
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    const string PUNC = " .,:;!?-'";
	char fname[100]; // file name
	cout << "enter file name: "; 
	cin >> fname;

	string shortest, longest, word;
	ifstream fin(fname); // opened the file for reading
	fin >> word;
	shortest = longest = word;
	while (getline(fin, word)) {
		if(word.size() > longest.size())
			longest = word;
		else if (word.size() < shortest.size())
			shortest = word;
	}

	cout << "The longest " << longest << " with a lenght " << longest.size() << endl;
	cout << "The shortest " << shortest << " with a lenght " << shortest.size() << endl;
	return 0;
}


output:
The longest New New New with a lenght 11
The shortest Nn with a lenght 2
Posted
Updated 11-May-22 20:00pm

You've read a line from the text file into word, now you need to break the line down into individual words. There's multiple ways to do that, but maybe you should look at using string.find_first_of() and string.substr(). You'd use find_first_of() to find the next puctuation character in the line, then use substr() to generate a single word, that you could then test to see if it is the longest or shortest word.

Documentation for std::string can be found here: std::basic_string - cppreference.com[^]
 
Share this answer
 
Comments
CPallini 12-May-22 1:53am    
5.
As K5054 already pointed out, you are retrieving the input in lines i.e. multiple words. In order to extract the words from a line, another option is using the Regular expressions library - cppreference.com[^] (see the sample code).
 
Share this answer
 
Comments
merano99 12-May-22 19:41pm    
5, The real way to do this.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900