0

Пишу программу, которая работает со структурой, вроде бы все получилось сделать, кроме редактирования записи, которая находится в файле. Во-первых в цикле начинает ругаться на scanf("%i" &num), и пишет "Выражение должно относиться к целочисленному типу", а если заменить на cin, то цикл идет бесконечно. В интернете не нашел кода для редактирования записи структуры из файла, так что помогите пожалуйста.

#include "pch.h"
#include <iostream>
#include <iterator>
#include <cstddef>
#include <string>
#include <fstream>
#define _CRT_SECURE_NO_WARNINGS
#ifdef _MSC_VER
#endif
using namespace std;
struct price {
    string tovar;
    string magaz;
    int num;
    bool operator()(int a) {
        num = a;
        return 0;
    }
    bool operator()(int a, string b) {
        num = a; tovar = b;
        return 0;
    }
    bool operator()(int a, string b, string c) {
        num = a; tovar = b; magaz = c;
        return 0;
    }
    bool iseecity() {
        cout << " Название товара - " << tovar;
        cout << " Магазин - " << magaz;
        cout << " Стоимость - " << num << endl;
        return 0;
    }
    bool iseebycity() {
        cout << " Магазин - " << magaz << "; ";
        cout << " Стоимость - " << num << endl;
        return 0;
    }
};
bool findcity(string str, price* a) {
    bool key = 0;
    for (size_t i = 0; i != 7; ++i) {
        if (str == (a[i].tovar)) {
            a[i].iseebycity();
            key = 1;
        }
    }
    return key;
}
int main() {
    const char* FName = "C:\\Users\\alexk\\source\\repos\\ConsoleApplication6\\ConsoleApplication6\\Base";
    setlocale(LC_ALL, "russian_russia");
    price air[7];
    int x1;
    int dann;
    string x2, x3;
    ofstream out(FName, ios::binary);
    cout << "Size of air: \n" << sizeof(price);
    cout << "Сколько раз вы хотите ввести данных:";
    cin >> dann;
    for (size_t i = 0; i != dann; ++i) {
        cout << "Введите стоимость " << (i + 1) << "-го товара: ";
        cin >> x1;
        cout << "Введите название " << (i + 1) << "-го товара: ";
        cin >> x2;
        cout << "Введите магазин в котором продается " << (i + 1) << "й товар: ";
        cin >> x3;
        air[i](x1, x2, x3);
        out.write((char*)&x1, sizeof(x1));
        out.write((char*)&x2, sizeof(x2));
        out.write((char*)&x3, sizeof(x3));
        cout << "\n";
    }
    //out.write((char*)&air, sizeof(air));
    string word;

    string plane;
    int num1;
    FILE *fout = fopen("Base", "r+b");
    cout << "Size of air: \n" << sizeof(air);
    cout << "Выберете действие: 1 - Поиск товара, 2 - дополнить файл, 3 - сортировка и вывод, 4 - коректирование записи.";
    cin >> num1;
    switch (num1)
    {
    case 1:
        cout << "Введите название товара для поиска: ";
        cin >> plane;
        if (!findcity(plane, air)) {
            cout << "В ячейке ничего нет!" << endl;
            break;
    case 2:
        cout << "Введите стоимость товара: ";
        cin >> x1;
        cout << "Введите название товара: ";
        cin >> x2;
        cout << "Введите магазин в котором продается товар: ";
        cin >> x3;
        air[dann + 1](x1, x2, x3);
        out.write((char*)&x1, sizeof(x1));
        out.write((char*)&x2, sizeof(x2));
        out.write((char*)&x3, sizeof(x3));
        cout << "\n";
        break;
    case 3:
        for (size_t i = 0; i != dann; ++i) {
            for (size_t j = i + 1; j != dann; ++j) {
                if ((air[i].tovar) > (air[j].tovar)) {
                    word = air[i].tovar;
                    air[i].tovar = air[j].tovar;
                    air[j].tovar = word;
                }
            }
        }
        for (size_t i = 0; i != dann; ++i) { air[i].iseecity(); }
        break;
    case 4:
        if (fout == NULL)
        {
            puts("Помилка відкриття файла\n");
            return 1;
        }
        fseek(fout, 0, SEEK_END);
        //int n_record = ftell(fout) / sizeof(air);
        int n_record = ftell(fout) / dann;
        int num;
        while (true)
        cout << "Bвeдіть номер запису або -1: " << endl;
        //cin >> num;
        scanf("%i" &num);
        if (num < 0 || num >= n_record) break;
        fseek(fout, num * sizeof(air), SEEK_SET);
        fread(&air, sizeof(air), 1, fout);
        printf("%s%5i%10.2f\n", air[num](x1, x2, x3));
        cout << "Bвeдите новую цену:  " << endl;     
        cin >> x1;
        air[num](x1);
        fseek(fout, num * sizeof(air), SEEK_SET);          
        fwrite(&air, sizeof(air), 1, fout);
        printf("%s%5i%10.2f\n", air[num](x1, x2, x3));
        }
        fclose(fout);      
        cout << "Коректування завершене" << endl;
        break;
    default:
        cout << "Выбраный не верный вариант";
    }

    out.close();
    system("pause");
    return 0;
}
3
  • scanf("%i" &num); - а запятую ставить не пробовали? scanf("%i", &num);? А еще вы наступили на все грабли, которые могли. См, например, ru.stackoverflow.com/questions/834447/…
    – Harry
    2 дек 2018 в 6:05
  • А еще - тут: ru.stackoverflow.com/questions/910758/… - это к вашим fwrite(&air, sizeof(air), 1, fout);...
    – Harry
    2 дек 2018 в 6:05
  • @Harry, пол вечера голову морочил с этим scanf, спасибо огромное. Да, почитаю
    – Alex
    2 дек 2018 в 6:35

0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Посмотрите другие вопросы с метками или задайте свой вопрос.