Hello. I have such a task:

  1. Find the 2 longest combo words
  2. Find all combined words in the file
  3. Count the total number of words in the file

That is, I enter a file in the program that contains words one by one in a line without spaces, say 1000 words. It is necessary that the program read all the words, find ordinary words (for example, cat) and a combined word (for example, catdog). The program must recognize this combined word and write it into an array for counting, and of all the combined, it must find the 2 longest.

I have the starting code, the program just searches for the 2 longest words, but not the combined ones:

#include "stdafx.h" #include <iostream> #include <fstream> #include <string> #include <algorithm> #include <set> using namespace std; struct Lcompare : binary_function<string, string, bool> { bool operator()(const string& p, const string& q) const { return p.size() > q.size(); } }; int main() { setlocale(LC_ALL, "Russian"); multiset<string, Lcompare > words; ifstream ifs("words.txt"); if (!ifs) { cout << "Ошибка, файл не найден \nПожалуйста повторите попытку" << endl; } else { while (!ifs.eof()) { string s; ifs >> s; words.insert(s); } // вывести на экран multiset<string, Lcompare >::iterator it = words.begin(); for (int i = 1; i <= 2 && it != words.end(); i++) cout << *it++ << endl; } system("pause"); return 0; } 
  • The word isolate is not a problem, it seems you have already seen. But with the "combined" people can distinguish, and the car? You need either a dictionary (less real), or a formula (more fantastic). - nick_n_a

1 answer 1

Suppose your sentence is an array of char . Then all you need is to count the number of spaces and add 1 - this will be the number of words. If before the proposal or after may also be a space, then you need to take this into account.

If the case is complicated by punctuation marks, or if there may be several spaces, then you can create an array of delimiter characters (for example,. You also need to take into account the fact that a comma and a space can occur, then you should check: if the previous character was not a separator, and the current character is a separator, then we increase the word count.

And the finished code here is unlikely to give someone

  • I will ask a question differently: - Andrey Stetsenko
  • Completely rephrased question. - Andrey Stetsenko