Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 5.00/3: Рейтинг темы: голосов - 3, средняя оценка - 5.00
35 / 1 / 1
Регистрация: 07.09.2014
Сообщений: 34

Разработка средства архивации

13.12.2014, 22:05. Показов 662. Ответов 4
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Добрый вечер имеется код,преподаватель сказал чтобы добавили класс Menu.
Программа компилируется но меню не запускается,сразу летит программа.
Проблема с классом Menu как можно правильно реализовать,чтобы он вызывал все методы описанные в классе Компресс..

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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
#include "stdafx.h"
#include <iostream>
 
#define BITS 12                     
#define HASHING_SHIFT BITS-8        
#define MAX_VALUE (1 << BITS) - 1   
#define MAX_CODE MAX_VALUE - 1      
#if BITS == 14
#define TABLE_SIZE 18041            
#endif                              
#if BITS == 13                       
#define TABLE_SIZE 9029
#endif
#if BITS <= 12
#define TABLE_SIZE 5021
#endif
 
using namespace std;
 
int *code_value;                    
unsigned int *prefix_code;          
unsigned char *append_character;    
unsigned char decode_stack[4000];
 
class CompressLZW 
    {
    public:
        
        int find_match(int hash_prefix,unsigned int hash_character) 
        {
            
            int index;
            int offset;
            index = (hash_character << HASHING_SHIFT) ^ hash_prefix;
            if (index == 0)
                offset = 1;
            else
                offset = TABLE_SIZE - index;
            
            while (1)   
            {
                if (code_value[index] == -1) 
                  return(index);    
                if (prefix_code[index] == hash_prefix && append_character[index] == hash_character)
                  return(index);    
                index -= offset;    
                if (index < 0)  
                  index += TABLE_SIZE;
            }
        }
        
        char *decode_string(unsigned char *buffer,unsigned int code)
        {
        int i=0;
            while (code > 255)  //
            {
                *buffer++ = append_character[code];             code=prefix_code[code]; 
                {
                    printf("Fatal error during code expansion.\n"); 
                    exit(-1);   
                }
            }
            *buffer=code;   
            return (char *)buffer;  
        }
 
    public:
 
        int input_code(FILE *input) 
        {
            unsigned int return_value;
            static int input_bit_count=0;
            static unsigned long input_bit_buffer=0L;
            while (input_bit_count <= 24)   
            {
                input_bit_buffer|=(unsigned long)getc(input)<<(24-input_bit_count); 
                input_bit_count += 8; 
            }
            return_value=input_bit_buffer >> (32-BITS); 
            input_bit_buffer <<= BITS;
            input_bit_count -= BITS;
            return(return_value);
        }
        void output_code(FILE *output,unsigned int code)        {
            static int output_bit_count=0;
            static unsigned long output_bit_buffer=0L;
            output_bit_buffer|=(unsigned long)code<<(32-BITS-output_bit_count);         output_bit_count += BITS;
            while (output_bit_count >= 8)
            {
                putc(output_bit_buffer >> 24,output);
                output_bit_buffer <<= 8;
                output_bit_count -= 8;
            }
        }
        void compress(FILE *input,FILE *output)
        {
            unsigned int next_code;
            unsigned int character;
            unsigned int string_code;
            unsigned int index;
            int i;
            next_code=256;                          
for (i=0;i<TABLE_SIZE;i++)  
                code_value[i]=-1;
            i=0;
            printf("Compressing...\n");
            string_code=getc(input);  
            while ((character=getc(input)) != (unsigned)EOF) 
            {
                if (++i==1000)            
                {                         
                    i=0;                  
                    printf("*");
                }
            
                index = find_match(string_code,character);                  if (code_value[index] != -1)                                    string_code=code_value[index];          
                else                                        
                {                                           
                    if (next_code <= MAX_CODE)
                                {
                        code_value[index]=next_code++;
                        prefix_code[index]=string_code;
                        append_character[index]=character;
                    }
                    output_code(output,string_code);
                    string_code=character;          
                }                                   
            }                                   
 
            output_code(output,string_code);  
            output_code(output,MAX_VALUE);    
            output_code(output,0);            
            printf("\n");
        }
 
                void expand(FILE *input,FILE *output)
        {
            unsigned int next_code;
            unsigned int new_code;
            unsigned int old_code;
            int character;
            int counter;
            unsigned char *string;
            next_code=256;                          counter=0;                              printf("Expanding...\n");
              old_code=input_code(input);                 character=old_code;                         putc(old_code,output);                
            while ((new_code=input_code(input)) != (MAX_VALUE))
            {
                if (++counter==1000) { counter=0; printf("*"); }
        
                if (new_code>=next_code)
                {
                    *decode_stack=character;
                    string = (unsigned char *)decode_string(decode_stack+1,old_code);
                }
                                else
                    string = (unsigned char *)decode_string(decode_stack,new_code);
                
                character=*string;
                while (string >= decode_stack)
                    putc(*string--,output);
            
                if (next_code <= MAX_CODE)
                {
                    prefix_code[next_code]=old_code;
                    append_character[next_code]=character;
                    next_code++;
                }
                old_code=new_code;
            }
            printf("\n");
        }
    };
 
    class Menu
    {
        static const int MAX_SIZE = 20;
        char * item[MAX_SIZE];
        int Size;
 
        public:
            
        ~Menu()
        {
        };
 
    int Menu::AddItem(char * k)
{
        if (Size == MAX_SIZE) return 0;
        item[Size] = new char[strlen(k) + 1];
        strcpy(item[Size], k);
        Size++;
        return Size;
}
 
 int Menu::ProcessMenu()
{
        int i, n;
        while (1)
        {
                system("cls");
                cout << "Введите номер действия" << endl;
                for (i = 0; i<Size; i++) cout << i + 1 << " - " << item[i] << endl;
                cout << Size + 1 << " - Выход" << endl;
                cin >> n;
                if (n>Size + 1 || n < 1) continue;
                break;
        }
        return n - 1;
}
 
 
Menu::Menu()
{
        AddItem("Compress.");
        AddItem("Expand.");
        AddItem("Exit.");
}
 
void  Menu::Process()
{
        int y;
        bool flag = true;
        while (flag)
        {
                system("cls");
                cout << "Выберите пункт меню : " <<endl;
                        while (flag)
                        {
                                switch (ProcessMenu())
                                {
                                case 1:
                                {
                                       void compress();
                                        system("pause");
                                        break;
                                }
                                case 2:
                                {
                                        void expand();
                                        system("pause");
                                        break;
                                }
                                case 3:
                                {
                                        exit;
                                        break;
                                default:
                                {
                                        flag = false;
                                        break;
                                }
                                }
                        }
                        flag = true;
                }
                if (y == 3) flag = false;
        }
}
};
 
 
int _tmain(int argc, _TCHAR* argv[])
{
    Menu m;
    m.Process();
    return 0;
}
0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
13.12.2014, 22:05
Ответы с готовыми решениями:

Метод архивации Шеннона-Фано
Не подскажите,может есть у кого исходник кода архивации(сжатия и восстановления) методом Шеннона-Фано на С++?

Кроссплатформенная библиотека для архивации
подскажите такую библиотекку обязательно кроссплатформенню я находил но они только под win или linux

Алгоритм архивации Лемпеля-Зива
Может есть у кого нибудь исходник, на любом языке, или кто может книгу подскажет где про это описано? Если кто поможет буду очень...

4
Неэпический
 Аватар для Croessmah
18149 / 10731 / 2067
Регистрация: 27.09.2012
Сообщений: 27,035
Записей в блоге: 1
13.12.2014, 22:13
Скорее всего летит в AddItem тут:
C++
1
item[Size] = new char[strlen(k) + 1];
ибо Size равен неизвестно чему.
Size инициализируйте в конструкторе класса.
0
35 / 1 / 1
Регистрация: 07.09.2014
Сообщений: 34
13.12.2014, 22:32  [ТС]
Спасибо вам!Инициализировал,и заработало сразу
теперь другая проблема я даже знаю где.

Пункты меню,планируется сделать чтобы выбрал пункт меню и сделал действие,но что-то я упустил не могу понять.

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
Menu::Menu()
{
        Size = 4;
        AddItem("1-Compress.");
        AddItem("2-Expand.");
        AddItem("3-Exit.");
}
 
        ~Menu()
        {
        };
 
    int Menu::AddItem(char * k)
{
        if (Size == MAX_SIZE) return 0;
        item[Size] = new char[strlen(k) + 1];
        strcpy(item[Size], k);
        Size++;
        return Size;
}
 
 int Menu::ProcessMenu()
{
        int i, n;
        while (1)
        {
                system("cls");
                cout << "Введите номер действия" << endl;
                for (i = 0; i<Size; i++) cout << i + 1 << " - " << item[i] << endl;
                cout << Size + 1 << " - Выход" << endl;
                cin >> n;
                if (n>Size + 1 || n < 1) continue;
                break;
        }
        return n - 1;
}
 
void  Menu::Process()
{
        int y;
        bool flag = true;
        while (flag)
        {
                system("cls");
                cout << "Выберите пункт меню : " <<endl;
                        while (flag)
                        {
                                switch (ProcessMenu())
                                {
                                case 1:
                                {
                                       void compress();
                                        system("pause");
                                        break;
                                }
                                case 2:
                                {
                                        void expand();
                                        system("pause");
                                        break;
                                }
                                case 3:
                                {
                                        exit;
                                        break;
                                default:
                                {
                                        flag = false;
                                        break;
                                }
                                }
                        }
                        flag = true;
                }
                if (y == 3) flag = false;
        }
}
0
Неэпический
 Аватар для Croessmah
18149 / 10731 / 2067
Регистрация: 27.09.2012
Сообщений: 27,035
Записей в блоге: 1
13.12.2014, 22:34
C++
1
Size = 0 ;// а не 4
0
35 / 1 / 1
Регистрация: 07.09.2014
Сообщений: 34
14.12.2014, 12:03  [ТС]
Подскажите пожалуйста как вызвать методы из класса CompressLZW в классе Menu?
То есть мои методы класса должны при нажатии соответствующей цифры выполнять действия.

Меню теперь работает,сделал Size=0,убрал лишние цифры Меню работает,спасибо

теперь осталось методы класса CompressLZW в меню добавить,перепробовал кучу вариантов.

Добавлено через 46 минут
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
#include "stdafx.h"
#include <iostream>
 
#define BITS 12                     
#define HASHING_SHIFT BITS-8        
#define MAX_VALUE (1 << BITS) - 1   
#define MAX_CODE MAX_VALUE - 1      
#if BITS == 14
#define TABLE_SIZE 18041            
#endif                              
#if BITS == 13                       
#define TABLE_SIZE 9029
#endif
#if BITS <= 12
#define TABLE_SIZE 5021
#endif
 
using namespace std;
 
int *code_value;                    
unsigned int *prefix_code;          
unsigned char *append_character;    
unsigned char decode_stack[4000];
 
class CompressLZW 
    {
    public: 
        int find_match(int hash_prefix,unsigned int hash_character) 
        {
            
            int index;
            int offset;
            index = (hash_character << HASHING_SHIFT) ^ hash_prefix;
            if (index == 0)
                offset = 1;
            else
                offset = TABLE_SIZE - index;
            
            while (1)   
            {
                if (code_value[index] == -1) 
                  return(index);    
                if (prefix_code[index] == hash_prefix && append_character[index] == hash_character)
                  return(index);    
                index -= offset;    
                if (index < 0)  
                  index += TABLE_SIZE;
            }
        }
        
        char *decode_string(unsigned char *buffer,unsigned int code)
        {
        int i=0;
            while (code > 255)  //
            {
                *buffer++ = append_character[code];             code=prefix_code[code]; 
                {
                    printf("Fatal error during code expansion.\n"); 
                    exit(-1);   
                }
            }
            *buffer=code;   
            return (char *)buffer;  
        }
    public:
 
        int input_code(FILE *input) 
        {
            unsigned int return_value;
            static int input_bit_count=0;
            static unsigned long input_bit_buffer=0L;
            while (input_bit_count <= 24)   
            {
                input_bit_buffer|=(unsigned long)getc(input)<<(24-input_bit_count); 
                input_bit_count += 8; 
            }
            return_value=input_bit_buffer >> (32-BITS); 
            input_bit_buffer <<= BITS;
            input_bit_count -= BITS;
            return(return_value);
        }
        void output_code(FILE *output,unsigned int code)        {
            static int output_bit_count=0;
            static unsigned long output_bit_buffer=0L;
            output_bit_buffer|=(unsigned long)code<<(32-BITS-output_bit_count);         output_bit_count += BITS;
            while (output_bit_count >= 8)
            {
                putc(output_bit_buffer >> 24,output);
                output_bit_buffer <<= 8;
                output_bit_count -= 8;
            }
        }
        void compress(FILE *input,FILE *output)
        {
            unsigned int next_code;
            unsigned int character;
            unsigned int string_code;
            unsigned int index;
            int i;
            next_code=256;                          
for (i=0;i<TABLE_SIZE;i++)  
                code_value[i]=-1;
            i=0;
            printf("Compressing...\n");
            string_code=getc(input);  
            while ((character=getc(input)) != (unsigned)EOF) 
            {
                if (++i==1000)            
                {                         
                    i=0;                  
                    printf("*");
                }
            
                index = find_match(string_code,character);                  if (code_value[index] != -1)                                    string_code=code_value[index];          
                else                                        
                {                                           
                    if (next_code <= MAX_CODE)
                                {
                        code_value[index]=next_code++;
                        prefix_code[index]=string_code;
                        append_character[index]=character;
                    }
                    output_code(output,string_code);
                    string_code=character;          
                }                                   
            }                                   
 
            output_code(output,string_code);  
            output_code(output,MAX_VALUE);    
            output_code(output,0);            
            printf("\n");
        }
 
                void expand(FILE *input,FILE *output)
        {
            unsigned int next_code;
            unsigned int new_code;
            unsigned int old_code;
            int character;
            int counter;
            unsigned char *string;
            next_code=256;                          counter=0;                              printf("Expanding...\n");
 
              old_code=input_code(input);                 character=old_code;                         putc(old_code,output);                
            while ((new_code=input_code(input)) != (MAX_VALUE))
            {
                if (++counter==1000) { counter=0; printf("*"); }
        
                if (new_code>=next_code)
                {
                    *decode_stack=character;
                    string = (unsigned char *)decode_string(decode_stack+1,old_code);
                }
                                else
                    string = (unsigned char *)decode_string(decode_stack,new_code);
                
                character=*string;
                while (string >= decode_stack)
                    putc(*string--,output);
            
                if (next_code <= MAX_CODE)
                {
                    prefix_code[next_code]=old_code;
                    append_character[next_code]=character;
                    next_code++;
                }
                old_code=new_code;
            }
            printf("\n");
        }
    };
 
class Menu
{
public:
    Menu()
    {
 
    }
    Menu vibr_punkt();
 
    ~Menu()
    {
 
    }
 
private:
 
};
 
Menu Menu::vibr_punkt()
{
    int item;
    CompressLZW m3;
    cout << "Выбрать пункт меню:" << endl;
    cout << "1 - Compress\n2 - Expand\n3 - exit" << endl;
    cin >> item;
    switch (item)
    {
    case 1:
        system("cls");
        &CompressLZW::compress;
    case 2:
        system("cls");
        &CompressLZW::expand;
    case 3:
        exit(EXIT_SUCCESS);
    default:
        cout << "Ошибка в вводе,попробуйте ещё:\n";
        return vibr_punkt();
    }
}
 
 
int _tmain(int argc, _TCHAR* argv[])
{
    setlocale(LC_ALL,"Russian");
    Menu m;
    &Menu::vibr_punkt;
    system("pause");
    return 0;
}
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
14.12.2014, 12:03
Помогаю со студенческими работами здесь

Потеря нулевых байт при архивации (алгоритм Хаффмана)
Неправильно архивирует pdf файлы Как мне сказали вся ошибка в функции BuildTable &quot;Вместо условия проверки отсутствия символа,...

Разработка программного средства системы поддержки принятия решений
Доброго времени суток! Дали задание разработать СППР. Но как это делается я вообще не понимаю. Есть у кого нибудь примеры решения...

Разработка программного средства для построения звёздного фрактала
Программное средство должно производить построение указанного фрактала исходя из различных начальных параметров,которые устанавливаются...

Разработка программного средства для построения кривой серпинского
нужна текстовая часть для курсовой.. помогите вот тема: разработка программного средства для построения кривой серпинского. вот...

Ошибка "планирование архивации могут только администраторы и операторы архива" при архивации
Здравствуйте! При попытке создать эжедневное копирование через &quot;Систему архивации Windows&quot; вылетает ошибка (во вложении) Хотя...


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

Или воспользуйтесь поиском по форуму:
5
Ответ Создать тему
Новые блоги и статьи
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 https:/ / www. cyberforum. ru/ blog_attachment. php?attachmentid=11680&amp;d=1772460536 Одним из. . .
Реалии
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 позволяет легко создать главного героя, который не проходит сквозь стены и перемещается с заданным трением о препятствия, которые можно располагать под углом, как верхнее. . .
Конвертировать закладки radiotray-ng в m3u-плейлист
damix 19.02.2026
Это можно сделать скриптом для PowerShell. Использование . \СonvertRadiotrayToM3U. ps1 <path_to_bookmarks. json> Рядом с файлом bookmarks. json появится файл bookmarks. m3u с результатом. # Check if. . .
Семь CDC на одном интерфейсе: 5 U[S]ARTов, 1 CAN и 1 SSI
Eddy_Em 18.02.2026
Постепенно допиливаю свою "многоинтерфейсную плату". Выглядит вот так: https:/ / www. cyberforum. ru/ blog_attachment. php?attachmentid=11617&stc=1&d=1771445347 Основана на STM32F303RBT6. На борту пять. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru