Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.52/21: Рейтинг темы: голосов - 21, средняя оценка - 4.52
0 / 0 / 0
Регистрация: 18.05.2019
Сообщений: 38

Ошибка "cannot seek string iterator after begin"

30.06.2020, 15:18. Показов 4382. Ответов 6

Студворк — интернет-сервис помощи студентам
Как исправить эту ошибку?

Задание: Разработанная демонстрационная программа должна позволять осуществлять добавление товаров, удаление товаров, сохранение текущего состояния в конфигурационный файл.
---
Файл: Text_PetShop.txt.

class=mammal name=cat cost=123.4 weight=30 nickname=Sasha
class=ampihian name=frog cost=14 kind=SDSs
class=ampihian name=gog cost=14 kind=Scl
class=house name=akvar const=13 volume=3 size=3000
class=feed name=Royal const=30 weight=2

---

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// main.cpp
 
#include <iostream>
#include <string>
#include <list>
#include <map>
#include <fstream>
#include "PetShop_Assortment.h"
#include "product_list.h"
 
using namespace std;
 
int main()
{
    setlocale(LC_ALL, "Russian");
    list<PetShop_Assortment*> _PetShop;
    product_factory<mammal> _factory;
 
    ifstream fin("Text_PetShop.txt");
    ofstream fout("Output_PetShop.txt");
 
    while (!fin.eof())
    {
        string _raw;
        getline(fin, _raw);
 
        list<string> _parametric_list;
        while (_raw.find(' ') != string::npos) {
            auto _probel = _raw.find(' ');
            _parametric_list.push_back(string(_raw.begin(), _raw.begin() + _probel));
            _raw = _raw.substr(_probel + 1, _raw.size() - 1);
        }
 
        _parametric_list.push_back(_raw);
        map<string, string> _splise_result;
 
        for (auto X : _parametric_list) {
            auto mesure = X.find('=');
            _splise_result.insert(make_pair(string(X.begin(), X.begin() + mesure), string(X.begin() + mesure + 1, X.end())));
        }
        _PetShop.push_back(_factory.get_product(_splise_result));
    }
 
    fin.close();
 
    for (auto product : _PetShop)
        if (product)
            cout << product->introduce() << endl;
 
    for (auto product : _PetShop)
        if (product)
            fout << product->introduce() << "\n";
 
    fout.close();
 
    for (auto product : _PetShop)
        delete product;
 
    system("pause");
    return 0;
}
---

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
//PetShop_Assortment.h
#pragma once
#include<string>
#include<map>
 
using namespace std;
 
 
class PetShop_Assortment
{
public:
    PetShop_Assortment();
    PetShop_Assortment(const std::string& _name_of_product, double cost) : _name_of_product(_name_of_product), cost(cost) {};
    const std::string& get_name_of_product() const;
    const double get_cost() const;
    virtual const std::string type_of_product() const = 0;
    virtual const std::string introduce() const;
    virtual ~PetShop_Assortment();
private:
    string _name_of_product;
    double cost;
};
 
 
 
class PetShop_factory_chain
{
public:
    PetShop_factory_chain() {
        _next = NULL;
    }
 
    ~PetShop_factory_chain() {
        delete _next;
    }
 
    PetShop_Assortment* get_product(const std::map<string, string> &_splise_result) const {
        if (is_mine(_splise_result))
            return create_product(_splise_result);
        else
            if (_next)
                _next->get_product(_splise_result);
            else
                default_cr();
    }
 
    void push_back(PetShop_factory_chain* _chain) {
        if (_next)
            _next->push_back(_chain);
        else
            _next = _chain;
    }
 
    bool remove(const std::map<string, string> &_splise_result) {
        if (_next) {
            if (_next->is_mine(_splise_result)) {
                auto tmp = _next;
                _next = _next->_next;
                tmp->_next = NULL;
                delete tmp;
                return true;
            }
            else
                return _next->remove(_splise_result);
        }
        else
            return false;
    }
 
protected:
    virtual bool is_mine(const std::map<string, string> &_splise_result) const = 0;
    virtual PetShop_Assortment* create_product(const std::map<string, string> &_splise_result) const = 0;
    virtual PetShop_Assortment* default_cr() const = 0;
 
private:
    PetShop_factory_chain* _next;
};
 
 
template <typename PRODUCT_TYPE>
class template_factory_chain : public PetShop_factory_chain
{
protected:
    bool is_mine(const std::map<string, string> &_splise_result) const {
        return _PRODUCT_TYPE.type_of_product() == _splise_result.find("class")->second;
    }
 
    PetShop_Assortment* create_product(const std::map<string, string> &_splise_result) const {
        return new PRODUCT_TYPE(_splise_result);
    }
 
    virtual PetShop_Assortment* default_cr() const {
        return NULL;
    }
 
private:
    PRODUCT_TYPE _PRODUCT_TYPE;
};
 
 
template <typename PRODUCT_TYPE, typename ... OTHERS>
class product_factory : public product_factory<OTHERS...> {
public:
    product_factory() {
        this->push_back(new template_factory_chain<PRODUCT_TYPE>);
    }
 
private:
    product_factory(const product_factory& orig) {}
    product_factory operator = (const product_factory& orig) { return *this; }
};
 
template <typename PRODUCT_TYPE>
class product_factory<PRODUCT_TYPE> : public product_factory<PRODUCT_TYPE, int> {};
 
 
template <>
class product_factory<int> : public PetShop_factory_chain {
protected:
    bool is_mine(const std::map<string, string> &_splise_result) const {
        return false;
    }
 
    PetShop_Assortment* create_product(const std::map<string, string> &_splise_result) const {
        return nullptr;
    }
 
    virtual PetShop_Assortment* default_cr() const {
        return nullptr;
    }
};
---

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//PetShop_Assortment.cpp
 
#include "PetShop_Assortment.h"
 
PetShop_Assortment::PetShop_Assortment() {}
 
 
const std::string &PetShop_Assortment::get_name_of_product() const
{
    return _name_of_product;
}
 
const double PetShop_Assortment::get_cost() const
{
    return cost;
}
 
const std::string PetShop_Assortment::introduce() const
{
    std::string tmp = "Тип товара: ";
    tmp = tmp + type_of_product() + " По цене: " + std::to_string(get_cost());
    return tmp;
}
 
PetShop_Assortment::~PetShop_Assortment() {}

---

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
//product_list.h
 
#pragma once
#include "PetShop_Assortment.h"
 
 
 
class mammal : public PetShop_Assortment {
 
public:
    mammal(const std::string &_name_of_product, double cost) : PetShop_Assortment(_name_of_product, cost) {}
    mammal(const std::map<std::string, std::string>&_splise_result) : PetShop_Assortment(_splise_result.find("name")->second, stod(_splise_result.find("cost")->second)), _weight(stod(_splise_result.find("weight")->second)), _nickname(_splise_result.find("nickname")->second) {}
 
    mammal() {}
 
    const std::string type_of_product() const
    {
        return "mammal";
    }
 
    const std::string introduce() const
    {
        std::string tmp = "Тип товара: ";
        tmp = tmp + type_of_product() + " Название товара: " + get_name_of_product() + " По цене: " + std::to_string(get_cost()) + " Вес: " + std::to_string(_weight) + " Имя: " + _nickname;
        return tmp;
    }
    
private:
    double _weight;
    string _nickname;
};
 
 
class amphibian : public PetShop_Assortment
{
public:
    amphibian(const std::string &_name_of_product, double cost) : PetShop_Assortment(_name_of_product, cost) {}
    amphibian(const std::map<std::string, std::string>&_splise_result) : PetShop_Assortment(_splise_result.find("name")->second, stod(_splise_result.find("cost")->second)), _kind(_splise_result.find("kind")->second) {}
 
    amphibian() {}
 
    const std::string type_of_product() const
    {
        return "amphibian";
    }
 
    const std::string introduce() const
    {
        std::string tmp = "Тип товара: ";
        tmp = tmp + type_of_product() + " Название товара: " + get_name_of_product() + " По цене: " + std::to_string(get_cost())  + " Вид: " + _kind;
        return tmp;
    }
private:
    string _kind;
 
};
 
 
class house: public PetShop_Assortment
{
public:
    house(const std::string &_name_of_product, double cost) : PetShop_Assortment(_name_of_product, cost) {}
    house(const std::map<std::string, std::string>&_splise_result) : PetShop_Assortment(_splise_result.find("name")->second, stod(_splise_result.find("cost")->second)), _volume(stod(_splise_result.find("volume")->second)), _size(stod(_splise_result.find("size")->second)) {}
 
    house() {}
 
    const std::string type_of_product() const
    {
        return "house";
    }
 
    const std::string introduce() const
    {
        std::string tmp = "Тип товара: ";
        tmp = tmp + type_of_product() + " Название товара: " + get_name_of_product() + " По цене: " + std::to_string(get_cost()) + " Объем: " + std::to_string(_volume) + " Размер: " + std::to_string(_size);
        return tmp;
    }
private:
    double _volume;
    double _size;
};
 
class feed : public PetShop_Assortment
{
public:
    feed(const std::string &_name_of_product, double cost) : PetShop_Assortment(_name_of_product, cost) {}
    feed(const std::map<std::string, std::string>&_splise_result) : PetShop_Assortment(_splise_result.find("name")->second, stod(_splise_result.find("cost")->second)), _weight(stod(_splise_result.find("weight")->second)) {}
    feed() {}
    
    const std::string type_of_product() const
    {
        return "feed";
    }
 
    const std::string introduce() const
    {
        std::string tmp = "Тип товара: ";
        tmp = tmp + type_of_product() + " Название корма: " + get_name_of_product() + " По цене: " + std::to_string(get_cost()) + " Вес: " + std::to_string(_weight);
        return tmp;
    }
private:
    double _weight;
};
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
30.06.2020, 15:18
Ответы с готовыми решениями:

Cannot seek vector bool iterator before begin
Имеется следующий код реализующий шифрование методом Хаффмана: using std::cout; using std::endl; using std::ios; using...

Сравнение string::iterator со string::reverse_iterator
Уважаемые форумчане, подскажите пожалуйста, как можно сравнить string::iterator и string::reverse_iterator, в частности что бы определить,...

string iterator
Почему выдает ошибку при перемещение итератора на другую позицию? #include &lt;iostream&gt; #include &lt;string&gt; using namespace...

6
0 / 0 / 0
Регистрация: 18.05.2019
Сообщений: 38
30.06.2020, 15:25  [ТС]
Ошибка
Миниатюры
Ошибка "cannot seek string iterator after begin"  
0
6772 / 4565 / 1844
Регистрация: 07.05.2019
Сообщений: 13,726
30.06.2020, 17:11
Цитата Сообщение от Meddan Посмотреть сообщение
auto mesure = X.find('=');
            _splise_result.insert(make_pair(string(X .begin(), X.begin() + mesure), string(X.begin() + mesure + 1, X.end())));
Здесь, наверное, тоже надо проверять, что mesure не равна std::string::npos

Добавлено через 3 минуты
Цитата Сообщение от Meddan Посмотреть сообщение
_raw = _raw.substr(_probel + 1, _raw.size() - 1)
_raw = _raw.substr(_probel + 1)
0
0 / 0 / 0
Регистрация: 18.05.2019
Сообщений: 38
30.06.2020, 20:29  [ТС]
oleg-m1973, спасибо, но к сожалению нет.

Добавлено через 2 минуты
Компилятор также выдает предупреждение:
Код: C4715; get_product значение возвращается не при всех путях выполнения; Файл: petshop_assortment.h; Строка: 44;
0
6772 / 4565 / 1844
Регистрация: 07.05.2019
Сообщений: 13,726
30.06.2020, 20:33
Цитата Сообщение от Meddan Посмотреть сообщение
Компилятор также выдает предупреждение:
Правильно выдаёт
C++
1
2
3
4
5
6
7
8
9
PetShop_Assortment* get_product(const std::map<string, string> &_splise_result) const 
{
    if (is_mine(_splise_result))
        return create_product(_splise_result);
    else if (_next)
            return _next->get_product(_splise_result);
 
    return default_cr();
}
0
0 / 0 / 0
Регистрация: 18.05.2019
Сообщений: 38
01.07.2020, 08:42  [ТС]
oleg-m1973, всё та же ошибка, но без предупреждения
0
6772 / 4565 / 1844
Регистрация: 07.05.2019
Сообщений: 13,726
01.07.2020, 10:54
Цитата Сообщение от Meddan Посмотреть сообщение
oleg-m1973, всё та же ошибка, но без предупреждения
У тебя код совершенно кривой. Отвалится может много где. Например вот здесь
Цитата Сообщение от Meddan Посмотреть сообщение
mammal(const std::map<std::string, std::string>&_splise_result) : PetShop_Assortment(_splise_result.find(" name")->second, stod(_splise_result.find("cost")->second)), _weight(stod(_splise_result.find("weight ")->second)), _nickname(_splise_result.find("nickname" )->second) {}
Пройдись отладчиком, F5 - F10, и посмотри в какой конкретно строчке отваливается
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
01.07.2020, 10:54
Помогаю со студенческими работами здесь

Библиотека string. Работа с iterator
#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;algorithm&gt; using namespace std; void mas(int n, string *words) { ...

Iterator - how return set of string
ребята, подскажите, как в итераторе из набора строк (hashset), найти и вернуть строки которые содержат определенную послед. символов, а...

Почему выдает ошибку в строке "for(Data::iterator p=stats.begin(); p!=stats.end(); ++p)"
&quot;Read a sequence of possibly whitespaceseparated (name,value) pairs, where the name is a single whitespaceseparated word and the value is...

Begin в итераторах string
Подскажите почему если begin ссылается на начало строки, и по идее первый символ, в выводе выходит второй символ строки? int...

Series,Matrix,String,Begin,If по С#
Series5. Дано целое число N и набор из N положительных вещественных чисел. Вывести в том же порядке целые части всех чисел из данного...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
7
Ответ Создать тему
Новые блоги и статьи
Модульный подход на примере F#
DevAlt 06.03.2026
В блоге дяди Боба наткнулся на такое определение: В этой книге («Подход, основанный на вариантах использования») Ивар утверждает, что архитектура программного обеспечения — это структуры,. . .
Управление камерой с помощью скрипта OrbitControls.js на Three.js: Вращение, зум и панорамирование
8Observer8 05.03.2026
Содержание блога Финальная демка в браузере работает на Desktop и мобильных браузерах. Итоговый код: orbit-controls-threejs-js. zip. Сканируйте QR-код на мобильном. Вращайте камеру одним пальцем,. . .
SDL3 для Web (WebAssembly): Синхронизация спрайтов SDL3 и тел Box2D
8Observer8 04.03.2026
Содержание блога Финальная демка в браузере. Итоговый код: finish-sync-physics-sprites-sdl3-c. zip На первой гифке отладочные линии отключены, а на второй включены:. . .
SDL3 для Web (WebAssembly): Идентификация объектов на Box2D v3 - использование userData и событий коллизий
8Observer8 02.03.2026
Содержание блога Финальная демка в браузере. Итоговый код: finish-collision-events-sdl3-c. zip Сканируйте QR-код на мобильном и вы увидите, что появится джойстик для управления главным героем. . . .
Реалии
Hrethgir 01.03.2026
Нет, я не закончил до сих пор симулятор. Эта задача сложнее. Не получилось уйти в плавсостав, но оно и к лучшему, возможно. Точнее получалось - но сварщиком в палубную команду, а это значит, в моём. . .
Ритм жизни
kumehtar 27.02.2026
Иногда приходится жить в ритме, где дел становится всё больше, а вовлечения в происходящее — всё меньше. Плотный график не даёт вниманию закрепиться ни на одном событии. Утро начинается с быстрых,. . .
SDL3 для Web (WebAssembly): Сборка библиотек: SDL3, Box2D, FreeType, SDL3_ttf, SDL3_mixer и SDL3_image из исходников с помощью CMake и Emscripten
8Observer8 27.02.2026
Недавно вышла версия 3. 4. 2 библиотеки SDL3. На странице официальной релиза доступны исходники, готовые DLL (для x86, x64, arm64), а также библиотеки для разработки под Android, MinGW и Visual Studio. . . .
SDL3 для Web (WebAssembly): Реализация движения на Box2D v3 - трение и коллизии с повёрнутыми стенами
8Observer8 20.02.2026
Содержание блога Box2D позволяет легко создать главного героя, который не проходит сквозь стены и перемещается с заданным трением о препятствия, которые можно располагать под углом, как верхнее. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru