#include <iostream>
#include <fstream>
#include <vector>
#include <windows.h>

using namespace std;

struct Word
{
    string word;
    int amount = 1;
};

int main()
{
    SetConsoleCP(65001);
    SetConsoleOutputCP(65001);
    system("cls");
    
    vector<Word> words;
    Word temp;
    ifstream input("input.txt");

    // ппроверка файла
    if(input.fail())
    {
        cout << "Ошибка чтения файла" << endl;
        Sleep(2000);
        return -1;
    }

    // записть в вектор
    while(input >> temp.word)
        words.push_back(temp);
    
    input.clear();
    input.seekg(0, ios::beg);
    //


    // вывод на экран
    string line;
    while(getline(input, line))
        cout << line << endl;

    input.close();
    //

    // поиск одинаковых слов
    bool same_words = false;

    for(int i = 0; i < words.size() - 1; i++)
        if(words[i].word != " ")
            for(int j = i + 1; j < words.size(); j++)
                if(words[i].word == words[j].word)
                {
                    words[i].amount++;
                    words[j].word = " ";
                    same_words = true;
                }

    // сортировка пузырьком (ну а хули)
    for (int i = 0; i < words.size() - 1; i++) 
        for (int j = 0; j < words.size() - i - 1; j++) 
            if (words[j].amount < words[j + 1].amount)
                swap(words[j], words[j + 1]);
            

    // еще 1 ошибка
    if(!same_words)
    {
        cout << "В тексте нету одинаковых слов";
        return -1;
    }

    // вывод слов
    cout << endl;
    for(int i = 0; i < words.size(); i++)
        if(words[i].amount != 1)
            cout << words[i].word << " - " << words[i].amount << endl;


    string output_name;
    cout << "\nВведите название файла для записи: ";
    cin >> output_name;


    // опять ошибка 
    ofstream output(output_name);
    if(output.fail())
    {
        cout << "Ошибка открытия файла!";
        Sleep(2000);
        return -1;
    }


    // запись
    for(int i = 0; i < words.size(); i++)
        if(words[i].amount != 1)
            output << words[i].word << " - " << words[i].amount << endl;

    cout << "Слова записаны";
    return 0;
}