15,901,426 members
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

## Solution 1

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[^]

CPallini 12-May-22 1:53am
5.

## Solution 2

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).