asyaevloeva
@asyaevloeva

Как записать строки в текстовый файл в определенном формате?

Пытаюсь создать словарь, где есть номер слова, слово и определение слова.
У меня пока эти данные нигде не хранятся. Мне нужно их получать из текстового файла, дозаписывать туда и сохранять в текстовый файл.
У меня есть функция View, которая выводит все данные в консоль. Хотелось бы, чтобы эти данные записывалось таким же образом в файл, как они отображаются в консоли.
мой код
#include <QCoreApplication>

#include <iostream>
#include <string>
#include <stdio.h>
#include <conio.h>
#include <iostream>
#include <fstream>
using namespace std;
//-------------------------------------
 //creating a class


vector<string> DictFinder (string filename) {

    ifstream files1(filename);
    vector<string> dict;
    string ss1;
    while(getline(files1, ss1)) dict.push_back(ss1);

    files1.close();
    return dict;
}


class Dictionary {

private:

public:
    string word;
    string definition;

    // constructor

    Dictionary() {
        this->word = "";
        this->definition = "";
    }

    string changeField () {
        string tmp;
        cout << "Enter new value: " << endl;
        cin >> tmp;
        return tmp;
    }

    void changeSubMenu() {
        char ch = '\0';
        cout << " Choose a field to edit: " << endl;
        cout << "(1) word " << endl;
        cout << "(2) definition " << endl;

        ch = _getch();

        int point = atoi(&ch);
        switch (point) {
            case 1 : this->word = this->changeField(); break;
            case 2 : this->definition = this->changeField(); break;
            default : break;
        }
    }
    void fields(string wordWhenConstrunct, string definitionWhenConstrunct) {
        this->word = wordWhenConstrunct;
        this->definition = definitionWhenConstrunct;
    }


    void OutOne() {
        std::cout << this->word << "\t";
        std::cout << this->definition << "\t";
    }

};



int ShowMenu();
void Create(Dictionary * A);
void Change(Dictionary * A);
void View(Dictionary A);

int ShowMenu()
{
    char ch = '\0';

    cout << "\n1 : Create" << endl;
    cout << "2 : Edit" << endl;
    cout << "3 : Delete" << endl;
    cout << "4 : View" << endl;
    cout << "5 : Exit" << endl;

    ch = _getch();

    return atoi(&ch);
}

int main()
{
    setlocale(LC_ALL, "Russian");
    fstream file;
    //ifstream ifstr("C:/qt_projects/dictionary/dict.txt");

    Dictionary Obj[100];
    int count = 0; float num = 0;


    while (1) {
      switch( ShowMenu() ) {
         case 1:
//          file.open("C:/qt_projects/dictionary/test.txt", std::ios_base::in | std::ios_base::binary);
//              if ( file.is_open() )//проверка существует файл или нет
//              {

//                 cout << " Create new objects: " << endl << " 'word', 'definition' " << endl;

//                 Create(&Obj[count]);
//                 count++;
//                  file.close();
//              }
//              else
//              {
//                  cout << "No records yet " << '\n';
//              }break;
             if (count < 1000) {
                 cout << " To create new objects fill a form below:" << endl << " 'word', 'definition' " << endl;

                Create(&Obj[count]);
                count++;

             }; break;
         case 2: {  cout << " There are " << count << " objects in the dictionary" << endl;
                    if (count > 0){
                        cout << " Enter the number of the object to edit: ";
                        cin >> num;
                        if (num <= 0) cout << "\n The number must be positive!" << endl;
                        else{
                            if ( (num - int(num)) != 0 )
                            cout << "\n The number must be an integer!" << endl;
                            else{
                                if (int(num) > count)
                                cout << " There is no " << int(num) << " object!" << endl;
                                else
                                Change(&Obj[int(num) - 1]);
                            }
                        }
                    }

                    else cout << " There are no objects in the dictionary" << endl;
                 };
                 break;
         case 3: {  cout << " There are " << count << " objects in the dictionary" << endl;
                    if (count > 0){

                        cout << " Enter the number of the object to remove: ";
                        cin >> num;

                        if (num <= 0) cout << "\n The number can't be negative!" << endl;
                        else{
                            if ( (num - int(num)) != 0 ) // if difference is more than zero, then the inputted number is with floating point
                            cout << "\n The number must be an integer!" << endl;
                            else{
                                if (int(num) <= count) {
                                    if (int(num) > count)
                                    cout << " There is no " << int(num) << " object!" << endl;
                                    else{
                                        for (int i = int(num); i < count; i++) {
                                        Obj[i - 1] = Obj[i];
                                        }
                                    count--;
                                    }
                                }
                            }
                        }
                    }
                    else cout << " There are no objects in the dictionary" << endl;
                 };
                 break;
         case 4: {  cout << " There are " << count << " objects in the dictionary" << endl;
                    if (count > 0){

                                    cout << "№\tword\tdefinition" << endl;
                                    for (int i = 0; i < count; i++) {
                                        cout << i+1 << "\t";
                                        View(Obj[i]);

                        }
                    }
                    else cout << " There are no objects in the dictionary" << endl;

                 };
                 break;

         case 5: return 0;
         default:
              break;
      }
   }
    return 0;
}



void Create(Dictionary * A) {

    string word, definition;
    cin >> word >> definition;
    A->fields(word, definition);
}

void Change(Dictionary * A){

    A->changeSubMenu();
}


void View(Dictionary A){

    A.OutOne();
//    fstream file;
//    file.open("C:/qt_projects/dictionary/test.txt", std::ios_base::out | std::ios_base::binary | std::ios_base::app); //открытие файла для записи
//    if (file)//проверка существует файл или нет
//    {

//        file.close();
//    }
//    else
//    {
//        cout << "Nope - " << '\n';
//    }
    cout << endl;
}


  • Вопрос задан
  • 203 просмотра
Пригласить эксперта
Ответы на вопрос 1
devalone
@devalone
̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы