Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
 
Рейтинг 4.69/978: Рейтинг темы: голосов - 978, средняя оценка - 4.69
16 / 17 / 0
Регистрация: 01.02.2012
Сообщений: 182
1

Решение всех упражнений из книги Р. Лафоре "Объектно-ориентированное программирование в С++"

01.02.2012, 17:47. Показов 191473. Ответов 322
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Хотя я и начинающий с++-шник. Хочу помочь другим людям. Здесь я буду выкладывать всё что мне удалось решить. В моих решениях будет много хедеров, делал я это в Dev C++. Ос Win 7 64 bit.

Начнём со второй главы:
Упражнение 1
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream> 
 
using namespace std;
 
int main()
{
   setlocale(0,"Rus");
   float gallons, cufeet;
 
   cout << "Введите количество галоннов: \n";
   cin >> gallons;
   cufeet = gallons / 7.481;
   cout << "Еквивалент в футах = " << cufeet << endl;
    
   return 0;
}

Упражнение 2
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream> 
#include <iomanip>
 
using namespace std;
 
int main()
{
   setlocale(0,"Rus");
   
    cout << 1990 << setw(8) << 135 << endl
           << 1991 << setw(8) << 7290 << endl 
           << 1992 << setw(8) << 11300 << endl
           << 1993 << setw(8) << 16200 << endl;
  
   return 0;
}

Упражнение 3
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream> 
 
using namespace std;
 
int main() 
{
    setlocale(0,"Rus");
    int var = 10;
 
    cout << var << endl;      
    var *= 2;                 
    cout << var-- << endl;    
    cout << var << endl;      
    return 0;
}

Упражнение 4
C++
1
2
3
4
5
6
7
8
9
10
#include <iostream> 
 
using namespace std;
 
int main() 
{
    setlocale(0,"Rus");
    cout<<"\nУ лукоморья дуб срубили\nКота на мясо порубили \nА по неведанным дорожкам\nШагали черти в босоножках\n"; 
    return 0;
}

Упражнение 5
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream> 
#include <ctype.h>
 
using namespace std;
 
int main() 
{
    setlocale(0,"Rus");
    char ch;
    cin >> ch;
    cout << islower(ch);  // При вводе строчной буквы будет 2 при прописной 0. Но есть нюанс, поддерживаються только англ буквы 
    return 0;
}


Упражнение 6
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream> 
 
using namespace std;
 
int main() 
{
    setlocale(0,"Rus");
 
    float a,b,c,d,f;
    cout << "Введите кол-во доларов"<<endl;
    cin >> f;
    b=f/1.487;
    c=f/0.172;
    a=f/0.584;
    d=f/0.00955;
    cout << f <<"доларов = "<< b<<" фунтов стерлинга"<<endl;
    cout << f <<"доларов = "<< c<<" франков"<<endl;
    cout << f <<"доларов = "<< a<<" немецких марок"<<endl;
    cout << f <<"доларов = "<< d<<" японских йен"<<endl;
    return 0;
}

Упражнение 7
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream> 
#include <iomanip>
 
using namespace std;
 
int main() 
{
    setlocale(0,"Rus");
    double f,c;
    cout << "Введите количество градусов по Цельсию"<<endl;
    cin >> c;
    f=c*1.8+32;
    cout <<setprecision(3)<< f << " градусов по Фаренгейту "<< endl; // Регуляция кол-во символов после запятой
    return 0;
}

Упражнение 8
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream> 
#include <iomanip>
 
using namespace std;
 
int main() 
{
    setlocale(0,"Rus");
    long pop1=2425785, pop2=47, pop3=9761;       
 
    cout << setfill('.') <<setw(8) << "LOCATION" << setw(12) // Обратите внимание на одинарные кавычки
           << "POPULATION" << endl
           <<setw(8) << "Portcity" << setw(12) << pop1 << endl
           << setw(8) << "Hightown" << setw(12) << pop2 << endl
           << setw(8) << "Lowville" << setw(12) << pop3 << endl;
    return 0;
}

Упражнение 9

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream> 
 
using namespace std;
 
int main() 
{
    setlocale(0,"Rus");
    char dummychar;
    double a,b,c,d,e,f;
    cout << "Введите а и b"<< endl;
    cin >>a>>dummychar>>b;
    cout << "Введите c и d"<<endl;
    cin >>c>>dummychar>>d;
    cout <<(b*c)+(d*a)<<dummychar<<(b*d)<<endl;
 
    return 0;
}

Упражнение 10 (Намучился с этой задачей)
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream> 
 
using namespace std;
 
int main() 
{
    setlocale(0,"Rus");
    float a,b,c,f;
    cout << "Введите количество фунтов"<<endl;
    cin >> a;
    cout << "Введите количество шиллингов"<<endl;
    cin >> b;
    cout << "Введите количество пенсов"<<endl;
    cin >> c;
    f = a+(b+c/12)/20;
    cout << "Количество фунтов = " << f << endl;
    return 0;
}

Упражнение 11
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream> 
#include <iomanip>
 
using namespace std;
 
int main() 
{
     setlocale(0,"Rus");
     cout << setiosflags(ios::left) <<setw(15) << "Фамилия"<< setw(15)<< "Имя"<<setw(15) << "Адресс"<<setw(15)<< "Город"<<endl
            <<setw(15)<< "Иванов"<<setw(15)<<"Петя"<<setw(15)<<"Кленовая 16"<<setw(10)<<"Москва"<<endl
            <<setw(15)<< "Иванов"<<setw(15)<<"Петя"<<setw(15)<<"Кленовая 16"<<setw(10)<<"Москва"<<endl
            <<setw(15)<< "Иванов"<<setw(15)<<"Петя"<<setw(15)<<"Кленовая 16"<<setw(10)<<"Москва"<<endl;
    return 0;
}

Упражнение 12 (это самая геморная программа на разработку которой ушло больше дня)
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream> 
 
using namespace std;
 
int main() 
{
setlocale(0,"Rus");
float a,b,z;
int c,k;
cout << "Введите кол-во футов " << endl;
cin >> a;
c = static_cast<int>(a);
b = a - c;
b *= 20;
k = static_cast<int>(b);
z = b - k;
z = z*12;
z = static_cast<int>(z);
k = static_cast<int>(k);
cout << c <<"."<< k <<"."<< z << endl;
return 0;
}
Это конец второй главы, третюю сделаю позже если будет нужна
 Комментарий модератора 
Пост обновлен по просьбе ТС
13
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
01.02.2012, 17:47
Ответы с готовыми решениями:

Решение всех упражнений из книги Р. Лафоре "Объектно-ориентированное программирование в С++"
Мне надо решение упражнений из книги Р. Лафоре &quot;Объектно-ориентированное программирование в С++&quot;....

Ищу ответы на задания из книги Лафоре Р. "Объектно-ориентированное программирование в С++" 4 издание.
Дошел до 10 главы, из каждой главы делал все 12 заданий, хочу проверить правильно ли я их делал. И...

Роберт Лафоре, "Объектно-ориентированное программирование на C++"
Здравствуйте, хотелось бы узнать мнение по поводу этой книги: стоит ли читать, или поискать другую?

Объектно-ориентированный анализ, Объектно-ориентированное проектирование, Объектно-ориентированное программирование
Моё задание: Система Авиакомпания. Авиакомпания имеет список рейсов. Диспетчер формирует летную...

322
0 / 0 / 0
Регистрация: 01.04.2015
Сообщений: 5
22.05.2015, 15:26 241
Author24 — интернет-сервис помощи студентам
Решил задачу 9 главы 11 двумя способами. Первый - гонка случайно определяемых фаворитов. Второй (bis) строго по определению задания в книге, т.е. фаворит определяется после прохождения половины дистанции. Старался вносить минимальные изменения в базовые классы (только изменил private на protected)

Кликните здесь для просмотра всего текста

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
268
269
270
271
272
273
274
275
276
277
//ex11_9bis
#include "C:\Programming\Лафоре_OOP_v_CPP\msoftCon\msoftcon.h"               //for console graphics
#include <iostream>                 //for I/O
#include <cstdlib>                  //for random()
#include <ctime>                    //for time()
 
using namespace std;
const int CPF = 5;                  //columns per furlong
const int maxHorses = 7;            //maximum number of horses
class track;                        //for forward references
////////////////////////////////////////////////////////////////
class horse
{
protected:
    const track* ptrTrack;        //pointer to track
    const int horse_number;       //this horse's number
    float finish_time;            //this horse's finish time
    float distance_run;           //distance run so far
public:                          //create the horse
    horse(const int n, const track* ptrT) :
        horse_number(n), ptrTrack(ptrT),
        distance_run(0.0)    //haven't moved yet
    {  }
    ~horse()                      //destroy the horse
    {
        /*empty*/
    }              //display the horse
    void display_horse(const float elapsed_time);
 
};  //end class horse
////////////////////////////////////////////////////////////////
class track
{
protected:
    horse* hArray[maxHorses];     //array of ptrs-to-horses
    int total_horses;             //total number of horses
    int horse_count;              //horses created so far
    const float track_length;     //track length in furlongs
    float elapsed_time;           //time since start of race
 
public:
    track(float lenT, int nH);    //2-arg constructor
    ~track();                     //destructor
    void display_track();         //display track
    void run();                   //run the race
    float get_track_len() const;  //return total track length
};  //end class track
//---------------------------------------------------------------
void horse::display_horse(float elapsed_time) //for each horse
{
    //display horse & number
    set_cursor_pos( 1 + int(distance_run * CPF),
                    2 + horse_number*2 );
    //horse 0 is blue
    set_color(static_cast<color>(cBLUE+horse_number));
    //draw horse
    char horse_char = '0' + static_cast<char>(horse_number);
    putch(' ');
    putch('\xDB');
    putch(horse_char);
    putch('\xDB');
    //until finish,
    if( distance_run < ptrTrack->get_track_len() + 1.0 / CPF )
    {
        if( rand() % 3 )              //skip about 1 of 3 ticks
            distance_run += 0.2F;      //advance 0.2 furlongs
        finish_time = elapsed_time;   //update finish time
    }
    else
    {
        //display finish time
        int mins = int(finish_time)/60;
        int secs = int(finish_time) - mins*60;
        cout << " Time=" << mins << ":" << secs;
    }
}  //end display_horse()
//---------------------------------------------------------------
track::track(float lenT, int nH) :  //track constructor
    track_length(lenT), total_horses(nH),
    horse_count(0), elapsed_time(0.0)
{
    init_graphics();           //start graphics
    total_horses =             //not more than 7 horses
        (total_horses > maxHorses) ? maxHorses : total_horses;
    for(int j=0; j<total_horses; j++)   //make each horse
        hArray[j] = new horse(horse_count++, this);
 
    time_t aTime;              //initialize random numbers
    srand( static_cast<unsigned>(time(&aTime)) );
    display_track();
}  //end track constructor
//---------------------------------------------------------------
track::~track()                     //track destructor
{
    for(int j=0; j<total_horses; j++) //delete each horse
        delete hArray[j];
}
//---------------------------------------------------------------
void track::display_track()
{
    clear_screen();                  //clear screen
    //display track
    for(int f=0; f<=track_length; f++)    //for each furlong
        for(int r=1; r<=total_horses*2 + 1; r++) //and screen row
        {
            set_cursor_pos(f*CPF + 5, r);
            if(f==0 || f==track_length)
                cout << '\xDE';         //draw start or finish line
            else
                cout << '\xB3';         //draw furlong marker
        }
}  //end display_track()
//---------------------------------------------------------------
void track::run()
{
    while( !kbhit() )
    {
        elapsed_time += 1.75;         //update time
        //update each horse
        for(int j=0; j<total_horses; j++)
            hArray[j]->display_horse(elapsed_time);
        wait(500);
    }
    getch();                         //eat the keystroke
    cout << endl;
}
//---------------------------------------------------------------
float track::get_track_len() const
{
    return track_length;
}
 
class comhorse:public horse
{
private:
    const int horse_number;
public:
    bool outstanding;  //флаг выдающейся лошади
    comhorse(const int n,bool outs, const track* ptrT): horse(n,ptrT), outstanding(outs), horse_number(n) { }
    void display_horse(float elapsed_time, bool speed_up);  // speed_up - сообщение, что надо ускориться
    int getHorseNumber()
    {
        return horse_number;
    }
    float getDistanceRun()
    {
        return distance_run;
    }
};
void comhorse::display_horse(float elapsed_time, bool speed_up) //for each horse
{
    //display horse & number
    set_cursor_pos( 1 + int(distance_run * CPF),
                    2 + horse_number*2 );
    //horse 0 is blue
    set_color(static_cast<color>(cBLUE+horse_number));
    //draw horse
    char horse_char = '0' + static_cast<char>(horse_number);
    /*if (outstanding)  horse_char = '0' + static_cast<char>(horse_number);
    else             horse_char = '+' + static_cast<char>(horse_number);*/
    putch(' ');
    if (outstanding) putch('+');  //графическое выделение выдающейся лошади
    else putch('\xDB');
    putch(horse_char);
    putch('\xDB');
    int clock=3;  //чем больше, тем меньше шансов отстать
    //until finish,
    if( distance_run < ptrTrack->get_track_len() + 1.0 / CPF )
    {
        if (outstanding && speed_up)  //если выдающеяся лошадь и ее преследуют или уже догнали\обогнали, то ускоряемся
        {
            distance_run += 0.1F;
            clock *=3;  // уменьшаем шанс потери хода
        }
        if( rand() % clock )              //skip about 1 of 3 ticks
            distance_run += 0.2F;      //advance 0.2 furlongs
        finish_time = elapsed_time;   //update finish time
    }
    else
    {
        //display finish time
        int mins = int(finish_time)/60;
        int secs = int(finish_time) - mins*60;
        cout << " Time=" << mins << ":" << secs;
    }
}
 
 
class comtrack:public track
{
private:
    comhorse* hArray[maxHorses];
    int horse_count;
    bool favorite_find;
 
public:
    comtrack(float lenT, int nH);
    ~comtrack()                     //track destructor
    {
        for(int j=0; j<total_horses; j++) //delete each horse
            delete hArray[j];
    }
    void run();
    bool check_rivals(int horse_num)  // проверка конкурентов
    {
        int d2=hArray[horse_num]->getDistanceRun();
        for (int j=0; j<total_horses; j++)
        {
            if (j != horse_num)
            {
                int d1=hArray[j]->getDistanceRun();
                if((d1 >= d2) || ((d2-d1) <= 0.1)) return true;  //сообщаем о первом же ближайщем конкуренте
            }
        }
        return false;
    }
 
    bool am_i_first(int horse_num)
    {
        int d2=hArray[horse_num]->getDistanceRun();
        for (int j=0; j<total_horses; j++)
        {
            int d1=hArray[j]->getDistanceRun();
            if(d2 > d1) return true ;  //сообщаем о первом же ближайщем конкуренте
        }
        return false;
    }
};
 
comtrack::comtrack(float lenT, int nH) :  track(lenT, nH), horse_count(0), favorite_find(false)
{
 
    for(int j=0; j<total_horses; j++)   //make each ComHorse
 
        hArray[j] = new comhorse(horse_count++,false, this);
}
 
void comtrack::run()
{
    while( !kbhit() )
    {
        elapsed_time += 1.75;         //update time
        //update each horse
        for(int j=0; j<total_horses; j++)
        {
            if (!favorite_find)
            {
                if(am_i_first(hArray[j]->getHorseNumber())&& hArray[j]->getDistanceRun()>track_length/2) //если впереди во второй половине мкачек, то становится фаворитом
                {
                    favorite_find = true;
                    hArray[j]->outstanding = true;
                }
            }
            //check_rivals
            hArray[j]->display_horse(elapsed_time, check_rivals(hArray[j]->getHorseNumber()));
        }
        wait(500);
    }
    getch();                         //eat the keystroke
    cout << endl;
}
//
 
/////////////////////////////////////////////////////////////////
int main()
{
    float length;
    int total;
    //get data from user
    cout << "\nEnter track length (furlongs; 1 to 12): ";
    cin >> length;
    cout << "\nEnter number of horses (1 to 7): ";
    cin >> total;
    comtrack theTrack(length, total);   //create the track
    theTrack.run();                  //run the race
    return 0;
}  //end main()
0
0 / 0 / 0
Регистрация: 01.04.2015
Сообщений: 5
22.05.2015, 15:36 242
вариант1

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
//ex9_11
#include "C:\Programming\Лафоре_OOP_v_CPP\msoftCon\msoftcon.h"               //for console graphics
#include <iostream>                 //for I/O
#include <cstdlib>                  //for random()
#include <ctime>                    //for time()
 
using namespace std;
const int CPF = 5;                  //columns per furlong
const int maxHorses = 7;            //maximum number of horses
class track;                        //for forward references
////////////////////////////////////////////////////////////////
 
inline bool isOutstanding()  //случайное определение
{
    //srand (time(NULL));
    return (rand()%2) ? true:false;
 
}
class horse
{
protected:
    const track* ptrTrack;        //pointer to track
    const int horse_number;       //this horse's number
    float finish_time;            //this horse's finish time
    float distance_run;           //distance run so far
public:                          //create the horse
    horse(const int n, const track* ptrT) :
        horse_number(n), ptrTrack(ptrT),
        distance_run(0.0)    //haven't moved yet
    {  }
    ~horse()                      //destroy the horse
    {
        /*empty*/
    }              //display the horse
    void display_horse(const float elapsed_time);
 
};  //end class horse
////////////////////////////////////////////////////////////////
class track
{
protected:
    horse* hArray[maxHorses];     //array of ptrs-to-horses
    int total_horses;             //total number of horses
    int horse_count;              //horses created so far
    const float track_length;     //track length in furlongs
    float elapsed_time;           //time since start of race
 
public:
    track(float lenT, int nH);    //2-arg constructor
    ~track();                     //destructor
    void display_track();         //display track
    void run();                   //run the race
    float get_track_len() const;  //return total track length
};  //end class track
//---------------------------------------------------------------
void horse::display_horse(float elapsed_time) //for each horse
{
    //display horse & number
    set_cursor_pos( 1 + int(distance_run * CPF),
                    2 + horse_number*2 );
    //horse 0 is blue
    set_color(static_cast<color>(cBLUE+horse_number));
    //draw horse
    char horse_char = '0' + static_cast<char>(horse_number);
    putch(' ');
    putch('\xDB');
    putch(horse_char);
    putch('\xDB');
    //until finish,
    if( distance_run < ptrTrack->get_track_len() + 1.0 / CPF )
    {
        if( rand() % 3 )              //skip about 1 of 3 ticks
            distance_run += 0.2F;      //advance 0.2 furlongs
        finish_time = elapsed_time;   //update finish time
    }
    else
    {
        //display finish time
        int mins = int(finish_time)/60;
        int secs = int(finish_time) - mins*60;
        cout << " Time=" << mins << ":" << secs;
    }
}  //end display_horse()
//---------------------------------------------------------------
track::track(float lenT, int nH) :  //track constructor
    track_length(lenT), total_horses(nH),
    horse_count(0), elapsed_time(0.0)
{
    init_graphics();           //start graphics
    total_horses =             //not more than 7 horses
        (total_horses > maxHorses) ? maxHorses : total_horses;
    for(int j=0; j<total_horses; j++)   //make each horse
        hArray[j] = new horse(horse_count++, this);
 
    time_t aTime;              //initialize random numbers
    srand( static_cast<unsigned>(time(&aTime)) );
    display_track();
}  //end track constructor
//---------------------------------------------------------------
track::~track()                     //track destructor
{
    for(int j=0; j<total_horses; j++) //delete each horse
        delete hArray[j];
}
//---------------------------------------------------------------
void track::display_track()
{
    clear_screen();                  //clear screen
    //display track
    for(int f=0; f<=track_length; f++)    //for each furlong
        for(int r=1; r<=total_horses*2 + 1; r++) //and screen row
        {
            set_cursor_pos(f*CPF + 5, r);
            if(f==0 || f==track_length)
                cout << '\xDE';         //draw start or finish line
            else
                cout << '\xB3';         //draw furlong marker
        }
}  //end display_track()
//---------------------------------------------------------------
void track::run()
{
    while( !kbhit() )
    {
        elapsed_time += 1.75;         //update time
        //update each horse
        for(int j=0; j<total_horses; j++)
            hArray[j]->display_horse(elapsed_time);
        wait(500);
    }
    getch();                         //eat the keystroke
    cout << endl;
}
//---------------------------------------------------------------
float track::get_track_len() const
{
    return track_length;
}
 
class comhorse:public horse
{
private:
    bool outstanding;  //флаг выдающейся лошади
    const int horse_number;
public:
    comhorse(const int n,bool outs, const track* ptrT): horse(n,ptrT), outstanding(outs), horse_number(n) { }
    void display_horse(float elapsed_time, bool speed_up);  // speed_up - сообщение, что надо ускориться
    int getHorseNumber()
    {
        return horse_number;
    }
    float getDistanceRun()
    {
        return distance_run;
    }
};
void comhorse::display_horse(float elapsed_time, bool speed_up) //for each horse
{
    //display horse & number
    set_cursor_pos( 1 + int(distance_run * CPF),
                    2 + horse_number*2 );
    //horse 0 is blue
    set_color(static_cast<color>(cBLUE+horse_number));
    //draw horse
    char horse_char = '0' + static_cast<char>(horse_number);
    /*if (outstanding)  horse_char = '0' + static_cast<char>(horse_number);
    else             horse_char = '+' + static_cast<char>(horse_number);*/
    putch(' ');
    if (outstanding) putch('+');  //графическое выделение выдающейся лошади
    else putch('\xDB');
    putch(horse_char);
    putch('\xDB');
    int clock=3;  //чем больше, тем меньше шансов отстать
    //until finish,
    if( distance_run < ptrTrack->get_track_len() + 1.0 / CPF )
    {
        if (outstanding && speed_up)  //если выдающеяся лошадь и ее преследуют или уже догнали\обогнали, то ускоряемся
        {
            distance_run += 0.1F;
            clock *=3;  // уменьшаем шанс потери хода
        }
        if( rand() % clock )              //skip about 1 of 3 ticks
            distance_run += 0.2F;      //advance 0.2 furlongs
        finish_time = elapsed_time;   //update finish time
    }
    else
    {
        //display finish time
        int mins = int(finish_time)/60;
        int secs = int(finish_time) - mins*60;
        cout << " Time=" << mins << ":" << secs;
    }
}
 
 
class comtrack:public track
{
private:
    comhorse* hArray[maxHorses];
    int horse_count;
 
public:
    comtrack(float lenT, int nH);
    ~comtrack()                     //track destructor
    {
        for(int j=0; j<total_horses; j++) //delete each horse
            delete hArray[j];
    }
    void run();
    bool check_rivals(int horse_num)  // проверка конкурентов
    {
        for (int j=0; j<total_horses; j++)
        {
            if (j != horse_num)
            {
                int d1=hArray[j]->getDistanceRun();
                int d2=hArray[horse_num]->getDistanceRun();
                if((d1 >= d2) || ((d2-d1) <= 0.1)) return true;  //сообщаем о первом же ближайщем конкуренте
            }
        }
        return false;
    }
};
 
comtrack::comtrack(float lenT, int nH) :  track(lenT, nH), horse_count(0)
{
 
    for(int j=0; j<total_horses; j++)   //make each ComHorse
 
        hArray[j] = new comhorse(horse_count++,isOutstanding(), this);
}
 
void comtrack::run()
{
    while( !kbhit() )
    {
        elapsed_time += 1.75;         //update time
        //update each horse
        for(int j=0; j<total_horses; j++)
            //check_rivals
            hArray[j]->display_horse(elapsed_time, check_rivals(hArray[j]->getHorseNumber()));
        wait(500);
    }
    getch();                         //eat the keystroke
    cout << endl;
}
//
 
/////////////////////////////////////////////////////////////////
int main()
{
    float length;
    int total;
    //get data from user
    cout << "\nEnter track length (furlongs; 1 to 12): ";
    cin >> length;
    cout << "\nEnter number of horses (1 to 7): ";
    cin >> total;
    comtrack theTrack(length, total);   //create the track
    theTrack.run();                  //run the race
    return 0;
}  //end main()
0
1 / 1 / 0
Регистрация: 20.04.2014
Сообщений: 140
25.05.2015, 16:29 243
Kimel, простите, а Вы задачи из главы 13 рассматривали?

Добавлено через 4 часа 15 минут
Ferrari F1, простите, а Вы кроме первой задачи в 13-ой главе еще другие рассматривали?
0
805 / 532 / 158
Регистрация: 27.01.2015
Сообщений: 3,017
Записей в блоге: 1
25.05.2015, 17:48 244
LittleMonkey, нее, мне и одного проекта хватило решить, я бы вобще взвыл, решая все 4 проекта. очень уж тяжкие номера, а эта прога с лифтом вобще вынос мозга, даже вникать в нее не стал
0
1 / 1 / 0
Регистрация: 20.04.2014
Сообщений: 140
25.05.2015, 20:50 245
Ferrari F1, очень жаль, мне как раз на среду задали эти задания
0
805 / 532 / 158
Регистрация: 27.01.2015
Сообщений: 3,017
Записей в блоге: 1
26.05.2015, 12:49 246
LittleMonkey, кто задал??? это где такой вуз, в котором преподают по Лафоре?
0
1 / 1 / 0
Регистрация: 20.04.2014
Сообщений: 140
26.05.2015, 16:52 247
Ferrari F1, в самом центре Киева)
0
805 / 532 / 158
Регистрация: 27.01.2015
Сообщений: 3,017
Записей в блоге: 1
26.05.2015, 22:27 248
LittleMonkey, вам обязательно делать именно все 4 проекта из 13 главы??? Мда, какой то зверский препод у вас. А скажите еще, вы все 12 упражнений после каждой главы сами от и до делали или отсюда копировали, когда сдавали преподу?
0
0 / 0 / 0
Регистрация: 01.04.2015
Сообщений: 5
29.05.2015, 14:20 249
Продолжаю публиковать решения некоторых задач, отличающиеся от приведенных в данном топике
Глава 12 задача 6

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
#include <iostream>
#include <fstream>
#include <windows.h>
 
 
using namespace std;
 
class name
{
private:
    string fname, otchestvo, familyname;
    unsigned long number;
public:
    name(): number(0) {}
    void kbd_get()
    {
        cout << "Введите имя: ";
        cin >> fname;
 
        cout << "Введите отчество: ";
        cin>>otchestvo;
 
        cout << "Введите фамилию: ";
        cin >> familyname;
 
        cout << "Введите номер: ";
        cin >> number;
    }
    bool disk_get(const char* file, int recnum);
    void disk_put(const char* file);
    void display() const
    {
        cout << "ФИО работника: "<< fname << " " << otchestvo << " " << familyname << endl;
        cout << "Номер работника: " << number<<endl;
    }
};
 
bool name::disk_get(const char* file, int recnum)
{
    ifstream infile;
    infile.open(file);
    if( !infile )                  //check for errors
    {
        cerr << "\nRead file error";
        exit(-1);
    }
    for (int i=1; i<= recnum; i++)
    {
        infile>>fname;
//          cout<<fname;
        infile>>otchestvo;
//          cout<<otchestvo;
        infile>>familyname;
//          cout<<familyname;
        infile>>number;
//          cout<<number<<endl;
//          if (infile.eof() && i == recnum) break;
        if (!infile)
        {
            cout << "Запись " << recnum << " не обнаружена"<<endl;
            number = 0;
            fname.clear();
            otchestvo.clear();
            familyname.clear();
            infile.close();
            return 0;
        }
    }
    infile.close();
    return 1;
}
 
void name::disk_put(const char* file)
{
    ofstream outfile;
    outfile.open(file, ios::app);        //open file
    if( !outfile )                  //check for errors
    {
        cerr << "\nCan't open file";
        exit(-1);
    }
    outfile<<fname<< ' ' <<otchestvo<< ' ' <<familyname<< ' ' <<number<< ' ' ;
    outfile.close();
}
 
 
 
int main()
{
    int ch;
    char* file = "ex12_4.txt";
    name myname;
    int recnum;
 
 
    SetConsoleOutputCP(1251);
    SetConsoleCP(1251);
 
    while (1)
    {
        cout << "Какую операцию произвести:"<<endl<< "  -1 Считать с файла." << endl
             << "  -2 Записать в файл." << endl << "  -3 Показать данные на дисплее." << endl
             << "  -4 Выйти из программы."<<endl;
 
        cin.clear();
        while (!(cin >> ch))
        {
            cin.clear();
            cin.sync();
        }
        switch (ch)
        {
        case 1:
        {
            cout << endl << "Ввведите номер требуемой записи ";
            cin >> recnum;
            myname.disk_get(file, recnum);
            break;
        }
        case 2:
            myname.disk_put(file);
            break;
        case 3:
            myname.display();
            break;
        case 4:
            exit (1);
        }
    }
    return 0;
}


Глава 12 задача 7

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
//charter 12 exercise 7
 
#include <iostream>
#include <fstream>
#include <windows.h>
 
 
using namespace std;
 
class name
{
private:
    string fname, otchestvo, familyname;
    unsigned long number;
    static fstream io_file;
public:
    name(): number(0) {}
    static bool openfile(char* filename)
    {
        io_file.open(filename,ios::in | ios::out | ios::app);
        if (io_file) return 1;
        else return 0;
    }
    static void close_file()
    {
        io_file.close();
    }
    static bool set_pos() //указатель чтения на начавло файла
    {
        if (io_file)
        {
            io_file.seekg(0, io_file.beg);
            return 1;
        }
        else return 0;
    }
    void display()
    {
        cout << "ФИО работника: "<< fname << " " << otchestvo << " " << familyname << endl;
        cout << "Номер работника: " << number<<endl;
    }
    bool disk_get(int);
    void disk_put();
};
 
bool name::disk_get(int recnum)  // прочесть запись №..
{
    name::set_pos();
    if( !io_file )                  //check for errors
    {
        cerr << "\nRead file error";
        exit(-1);
    }
    for (int i=1; i<= recnum; i++)
    {
        io_file>>fname;
//          cout<<fname;
        io_file>>otchestvo;
//          cout<<otchestvo;
        io_file>>familyname;
//          cout<<familyname;
        io_file>>number;
//          cout<<number<<endl;
//          if (infile.eof() && i == recnum) break;
        if (!io_file)
        {
            cout << "Запись " << recnum << " не обнаружена"<<endl;
            number = 0;
            fname.clear();
            otchestvo.clear();
            familyname.clear();
            io_file.clear();
            return 0;
        }
    }
    return 1;
}
 
void name::disk_put()
{
    if( !io_file )                  //check for errors
    {
        cerr << "\nCan't open file";
        exit(-1);
    }
 
    if (fname.empty())
    {
        cout << "нет данных для записи"<<endl;
    }
    else
    {
        io_file<<fname<< ' ' <<otchestvo<< ' ' <<familyname<< ' ' <<number<< ' ' ;
 
        if( !io_file )                  //check for errors
        {
            cerr << "\nCan't write to the file";
            exit(-1);
        }
    }
}
 
fstream name::io_file;
 
int main()
{
    int ch;
    char* file = "ex12_4.txt";
    name myname;
    int recnum;
 
 
    SetConsoleOutputCP(1251);
    SetConsoleCP(1251);
 
    name::openfile(file);
    while (1)
    {
        cout << "Какую операцию произвести:"<<endl<< "  -1 Считать с файла." << endl
             << "  -2 Записать в файл." << endl << "  -3 Показать данные на дисплее." << endl
             << "  -4 Выйти из программы."<<endl;
 
        cin.clear();
        while (!(cin >> ch))
        {
            cin.clear();
            cin.sync();
        }
        switch (ch)
        {
        case 1:
        {
            cout << endl << "Ввведите номер требуемой записи ";
            cin >> recnum;
            myname.disk_get(recnum);
            break;
        }
        case 2:
            myname.disk_put();
            break;
        case 3:
            myname.display();
            break;
        case 4:
            name::close_file();
            exit (1);
        }
    }
    return 0;
}
0
0 / 0 / 0
Регистрация: 01.04.2015
Сообщений: 5
01.06.2015, 11:19 250
Глава 12 задача 9

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
#include <iostream>
#include <conio.h>
#include <stdlib.h>
#include <ctype.h>
#include <cstring>
#include <string>
#include <cmath>
#include <stdio.h>
 
 
using namespace std;
 
int gcd(int a, int b) // Поиск общего знаменателя (точнее НОД)
{
    a=abs(a);
    b=abs(b);
    return b? gcd(b, a % b) : a;
}
 
class fraction
{
private:
    int numerator;
    int denominator;
 
    void rtf()
    {
        int cf = gcd(numerator, denominator);
        numerator /= cf;
        denominator /= cf;
    }   //сократить дробь
 
public:
    fraction(int num=0, int denom=1): numerator(num), denominator(denom) {}
    //fraction(): numerator(0), denominator(1) {}
    //fraction fractionsum(fraction& str1, fraction& str2)
 
    fraction operator+(fraction str2)
    {
        fraction temp = fraction((numerator*str2.denominator + denominator*str2.numerator), denominator*str2.denominator);
        temp.rtf();
        return temp;
    }
    fraction operator-(fraction str2);
    fraction operator /(fraction str2);
    fraction operator *(fraction str2);
 
    bool operator ==(fraction str2);
    bool operator !=(fraction str2);
    friend istream& operator >> (istream&, fraction&);
    friend ostream& operator << (ostream&, fraction&);
};
 
istream& operator >> (istream& os, fraction& fr)
{
    char str;
    int temp;
 
    os>>fr.numerator;
    if (!os) return os;
    os>>str;
    if (strchr("+-:*", str))
    {
        os>>temp;
        os.putback(49);
        os.putback('/');
        os.putback(temp+48);
        os.putback(str);
        return os;
    }
    else if (str == '/')
    {
        os>>fr.denominator;
    }
    else os.setstate( ios_base::badbit );
    return os;
}
 
ostream& operator << (ostream& os, fraction& fr)
{
    int interger, minus_s = 0;
 
    int num = abs(fr.numerator), den = fr.denominator;
 
    if (fr.numerator < 0) minus_s = 1;
 
 
    if (num >= den)
    {
        interger = num/den;
        num -= (interger*den);
        if (minus_s) os << "-";
        os << interger;
        if (num > 0) os << " и " << num << "/" <<den;
        os << endl;
 
    }
    else if (num > 0)
    {
        if (minus_s) os << "-";
        os << num << "/" << den << endl;
    }
    else os << 0 << endl;
    return os;
 
}
 
 
fraction fraction::operator -(fraction str2)
{
    fraction sum;
    sum.numerator = numerator*str2.denominator - denominator*str2.numerator;
    sum.denominator = denominator*str2.denominator;
    sum.rtf();
 
    return sum;
}
 
fraction fraction::operator /(fraction str2)
{
    fraction sum;
    sum.numerator = numerator*str2.denominator;
    sum.denominator = denominator*str2.numerator;
    sum.rtf();
 
    return sum;
}
 
fraction fraction::operator*(fraction str2)
{
    fraction sum;
    sum.numerator = numerator*str2.numerator;
    sum.denominator = denominator*str2.denominator;
    sum.rtf();
 
    return sum;
}
 
bool fraction::operator ==(fraction str2)
{
    return (numerator == str2.numerator && denominator == str2.denominator) ? true : false;
}
 
bool fraction::operator !=(fraction str2)
{
    return (numerator!= str2.numerator || denominator != str2.denominator) ? true : false;
}
 
 
int main()
{
    setlocale(LC_CTYPE, "rus");
    char oper;
 
    do
    {
        fraction fr1, fr2, sum;
        cout << endl << "Введите через пробел: первую дробь операцию вторую дробь" << endl;
 
        do
        {
            cin.clear();
            cin.sync();
            cin >> fr1 >> oper >> fr2;
            if (!cin || !strchr("+-*/:", oper))
            {
                cout << "Неправильный формат"<<endl;
                cin.setstate( ios_base::badbit );
            }
        }
        while (!cin);
 
        switch(oper)
        {
        case '+':
            sum = fr1+fr2;
 
            break;
        case '-':
            sum = fr1-fr2;
 
            break;
        case '*':
            sum = fr1* fr2;
 
            break;
        case '/':
        case ':':
            sum = fr1/ fr2;
 
            break;
        }
        cout << sum;
 
        cout << "\nПродолжить ? (Y/N)";
    }
    while (!strchr("Nn", getche()));
 
    return(0);
}
0
0 / 0 / 0
Регистрация: 09.06.2015
Сообщений: 12
09.06.2015, 18:18 251
Здравствуйте!
Помогите, пожалуйста, найти ошибку в коде к упражнению 7 главы 7 (при нажатии 'y' после запроса происходит зацикливание). Использую Visual Studio 2013 Professional.
Кликните здесь для просмотра всего текста
/
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
/преобразование денежной строки в число
#include <iostream>
#include <stdlib.h>
#include <cstring>
#include <iomanip>
using namespace std;
 
const int MAX = 20;
class money
{
private:
    char textDollar[MAX];
public:
    money()
    {
        textDollar[0] = '\0';
    }
    void getmoney()
    {
        cout << "Введите денежную сумму вида $000,000,000.00" << endl;
        cin.get(textDollar, MAX);
    }
    long double mstold()
    {
        char textDollar_without_signs[MAX];           //текстовая строка, включающая только цифры и десятичную точку
        long double digitDollar;                      //числовое значение денежной суммы
        int k = 0;                       //индекс массива textDollar_without_signs[]
        for (int j = 0; j < strlen(textDollar); j++)
            if ((textDollar[j] == '1') || (textDollar[j] == '2') || (textDollar[j] == '3')            //рассматриваем только цифры (0-9)
                || (textDollar[j] == '4') || (textDollar[j] == '5') || (textDollar[j] == '6')         
                || (textDollar[j] == '7') || (textDollar[j] == '8') || (textDollar[j] == '9')
                || (textDollar[j] == '0') || (textDollar[j] == '.'))                                   //и десятичную точку
            {
                textDollar_without_signs[k] = textDollar[j];                                          //копируем нужный символ в textDollar_without_signs[0]
                k++;
            }
        textDollar_without_signs[k] = '\0';                                            //завершаем строку нулем
        digitDollar = strtold(textDollar_without_signs, NULL);
 
        return digitDollar;
    }
};
 
int main()
{
    system("chcp 1251 > nul");                             //для нормального отображения кириллицы
    
    money textMoneySum; char ch = 'y'; int n = 0;
    do
    {
        textMoneySum.getmoney();
        cout << setiosflags(ios::fixed) << setiosflags(ios::showpoint)
            << setprecision(2) << textMoneySum.mstold() << endl;
        cout << "Продолжить (y/n)? ";
        cin >> ch;
    } while (ch != 'n');
    cout << endl;
 
    return 0;
}
0
805 / 532 / 158
Регистрация: 27.01.2015
Сообщений: 3,017
Записей в блоге: 1
09.06.2015, 18:41 252
Mengelion,

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
#include <iostream>
#include <windows.h>
#include <stdlib.h>
#include <cstring>
#include <iomanip>
using namespace std;
 
const int MAX = 20;
class money
{
private:
    char textDollar[MAX];
public:
    money()
    {
        textDollar[0] = '\0';
    }
    void getmoney()
    {
        cin.clear();
        cin.sync();
        cout << "Введите денежную сумму вида $000,000,000.00" << endl;
        cin.get(textDollar, MAX);
    }
    long double mstold()
    {
        char textDollar_without_signs[MAX];           //текстовая строка, включающая только цифры и десятичную точку
        long double digitDollar;                      //числовое значение денежной суммы
        int k = 0;                       //индекс массива textDollar_without_signs[]
        for (int j = 0; j < strlen(textDollar); j++)
        if ((textDollar[j] == '1') || (textDollar[j] == '2') || (textDollar[j] == '3')            //рассматриваем только цифры (0-9)
            || (textDollar[j] == '4') || (textDollar[j] == '5') || (textDollar[j] == '6')
            || (textDollar[j] == '7') || (textDollar[j] == '8') || (textDollar[j] == '9')
            || (textDollar[j] == '0') || (textDollar[j] == '.'))                                   //и десятичную точку
        {
            textDollar_without_signs[k] = textDollar[j];                                          //копируем нужный символ в textDollar_without_signs[0]
            k++;
        }
        textDollar_without_signs[k] = '\0';                                            //завершаем строку нулем
        digitDollar = strtold(textDollar_without_signs, NULL);
 
        return digitDollar;
    }
};
 
int main()
{
    SetConsoleCP(1251);
    SetConsoleOutputCP(1251);
    money textMoneySum; char ch = 'y'; int n = 0;
    do
    {
        textMoneySum.getmoney();
        cout << setiosflags(ios::fixed) << setiosflags(ios::showpoint)
            << setprecision(2) << textMoneySum.mstold() << endl;
        cout << "Продолжить (y/n)? ";
        cin >> ch;
    } while (ch != 'n');
    cout << endl;
    system("pause");
    return 0;
}
1
0 / 0 / 0
Регистрация: 09.06.2015
Сообщений: 12
09.06.2015, 19:17 253
Ferrari F1, спасибо большое! Проблема решилась добавлением cin.sync(); в метод getmoney(), также оказалось, что проблема отсутствует, если использовать cin вместо cin.get().
0
0 / 0 / 0
Регистрация: 09.06.2015
Сообщений: 12
22.06.2015, 14:25 254
Здравствуйте, господа!
Пробую выполнить упражнение 11 главы 7 так, как это указано в книге. Там говорится, что для преобразования из long double в текст нужно использовать объект ostrstream, о котором в этой главе ничего не сказано. В интернете нашёл фрагмент кода, который приведён в строках 31-33. Выполнение программы происходит с ошибкой Debug Assertion Failed!(подозреваю, что ошибка именно в строках 31-33, но не уверен). Если возможно, укажите на ошибку в листинге.
Кликните здесь для просмотра всего текста

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
//преобразование числа в денежную строку
#include <strstream>
#include <iostream>
#include <string>
using namespace std;
 
class money
{
private:
    long double digitDollar;
public:
    money()
    {
        digitDollar = 0.00;
    }
    void getmoney()
    {
        cout << "Введите денежную сумму в виде числа: ";
        cin >> digitDollar;
    }
    string ldtoms() 
    {
        string textDollar, ustring;
        int n, m, i;
        
        if ((digitDollar < 0.00) || (digitDollar > 9999999999999990.00))           //проверка значения введенной денежной суммы
        {
            textDollar = "Недопустимое значение!"; return textDollar;
        }
        
        ostrstream ost;            //преобразование в строку без знака доллара и пробелов
        ost << digitDollar;
        ustring = ost.str();
        
        for (int j = 0; j < ustring.size(); j++)                  //полное копирование из ustring в textDollar;
            textDollar[j] = ustring[j];
        
        n = textDollar.find_first_not_of("0");              //ищем позицию, где не встречается '0'             
        textDollar.erase(0, n);                             //удаляем нули из начала
 
        m = textDollar.find_first_of(".");                //ищем позицию, где встречается "."
        switch (m % 3)                                       //определение места, где должен быть первый пробел  
        {
        case 1: i = 1; break;
        case 2: i = 2; break;
        case 0: i = 3; break;
        }
 
        int p = 0;
        while (textDollar[i] != '.') //проходим каждый символ, начиная с первого пробела, пока не увидим точку.
        {
            int jj = p % 4;               //через каждые 3 символа
            if (jj == 0)
                textDollar.insert(i, " "); //вставляем пробел
            p++;
            i++;
        }
 
        textDollar.insert(0, "$");
        textDollar[textDollar.size()] = '\0';
 
        return textDollar;
    }
};
 
int main()
{
    system("chcp 1251 > nul");                             //для нормального отображения кириллицы
 
    money textMoney;
    string s1;
    char ch = 'y';
    do
    {
        textMoney.getmoney();
        s1 = textMoney.ldtoms();
        cout << s1 << endl;
        cout << "Продолжить (y/n)? ";
        cin >> ch;
    } while (ch != 'n');
    cout << endl;
 
    return 0;
}
0
805 / 532 / 158
Регистрация: 27.01.2015
Сообщений: 3,017
Записей в блоге: 1
22.06.2015, 16:56 255
Mengelion, cмотри мой пост с решением задач из этой главы, я использовал объект класса sstream
1
0 / 0 / 0
Регистрация: 09.06.2015
Сообщений: 12
23.06.2015, 10:10 256
Ferrari F1, воспользовался Вашим постом, но та же беда.
В своем листинге заменил
C++
1
2
3
ostrstream ost;
ost << digitDollar;
ustring = ost.str();
на
C++
1
2
3
stringstream ost;
ost << fixed << digitDollar;
ost >> ustring;
Предполагаю, что ошибка всё же не в преобразовании. При отладке увидел, что ustring заполняется не только вводимым числом из digitDollar, но и после него вставляет огромное количество непонятных элементов, и вылазит ошибка string subscript out of range.

Добавлено через 16 часов 24 минуты
Всем спасибо, действительно при использовании объекта ostringstream преобразование будет таким, как надо. А ошибка была банальной)) Привожу своё решение этого многострадального упражнения, может кому-то пригодится.
Глава 7, упражнение 11
Кликните здесь для просмотра всего текста
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
//преобразование числа в денежную строку
#include <sstream>
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
 
class money
{
private:
    long double digitDollar;
public:
    money()
    {
        digitDollar = 0.00;
    }
    void getmoney()
    {
        cout << "Введите денежную сумму в виде числа: ";
        cin >> digitDollar;
    }
    string ldtoms() 
    {
        string textDollar, ustring;
        int n, m, i;
        
        if ((digitDollar < 0.00) || (digitDollar > 9999999999999990.00))           //проверка значения введенной денежной суммы
        {
            textDollar = "Недопустимое значение!"; return textDollar;
        }
        
        ostringstream ost;            //преобразование в строку без знака доллара и запятых
        ost << setiosflags(ios::fixed) << setiosflags(ios::showpoint) << setprecision(2) << digitDollar;
        ustring = ost.str();
 
        textDollar = ustring;                                       //полное копирование из ustring в textDollar;
        
        n = textDollar.find_first_not_of("0");              //ищем позицию, где не встречается '0'             
        textDollar.erase(0, n);                             //удаляем нули из начала (необязательно, так как они сами удаляются)
 
        m = textDollar.find_first_of(".");                //ищем позицию, где встречается "."
        switch (m % 3)                                       //определение места, где должен быть первый пробел  
        {
        case 1: i = 1; break;
        case 2: i = 2; break;
        case 0: i = 3; break;
        }
 
        int p = 0;
        while (textDollar[i] != '.') //проходим каждый символ, начиная с первого пробела, пока не увидим точку.
        {
            int jj = p % 4;               //через каждые 3 символа
            if (jj == 0)
                textDollar.insert(i, " "); //вставляем пробел
            p++;
            i++;
        }
 
        textDollar.insert(0, "$");
        textDollar[textDollar.size()] = '\0';
 
        return textDollar;
    }
};
 
int main()
{
    system("chcp 1251 > nul");                             //для нормального отображения кириллицы
 
    money textMoney;
    string s1;
    char ch = 'y';
    do
    {
        textMoney.getmoney();
        s1 = textMoney.ldtoms();
        cout << s1 << endl;
        cout << "Продолжить (y/n)? ";
        cin >> ch;
    } while (ch != 'n');
    cout << endl;
 
    return 0;
}
0
0 / 0 / 0
Регистрация: 01.04.2015
Сообщений: 5
23.06.2015, 15:33 257
Наиболее интересная задача из 15 главы 12-я (или 13-я если книга с ошибкой)
Глава 15 задание 12

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
#include <fstream>
#include <algorithm>
#include <iostream>
#include <map>
#include <clocale>
#include <iomanip>
 
using namespace std;
 
int main()
{
    string fname, word;
    map <string,int, less<string> > fr_table;
 
    setlocale(LC_ALL,"Russian");
 
    cout << "Enter file name to be analyzed ";
    cin >> fname;
 
    ifstream infile(fname);
    if (!infile)
    {
        cout << "Error opening file " << fname;
        exit (-1);
    }
 
    map <string,int, less<string> >::iterator ptr_fr_table;
 
    while (!infile.eof())
    {
        infile >> word;
        word.erase (remove_if (word.begin (), word.end (), ::ispunct), word.end ());
        if (word.begin() == word.end()) continue;                                    //пустышки не считаем
        transform(word.begin(), word.end(), word.begin(), ::tolower);
 
        if ((ptr_fr_table=fr_table.find(word)) != fr_table.end()) (*ptr_fr_table).second++;
        else fr_table[word] = 1;
    }
 
    ofstream outfile("result.txt");
    if (!outfile)
    {
        cout << "Error opening resulting file";
        exit (-1);
    }
    for(ptr_fr_table = fr_table.begin(); ptr_fr_table != fr_table.end(); ptr_fr_table++)
        outfile << setw(30) << left<< (*ptr_fr_table).first << setw(4) << right << (*ptr_fr_table).second <<endl;
    outfile.close();
    if (!outfile.fail()) cout << "Вывод в файл \"result.txt\" произведен успешно!";
    else
    {
        cout << "Ошибка при записи в файл";
        exit (-1);
    }
    return 0;
}
0
0 / 0 / 0
Регистрация: 09.06.2015
Сообщений: 12
06.07.2015, 16:25 258
Здравствуйте! Решения многих задач из Лафоре приведены также здесь: http://una.co.uk/Instructor/
0
0 / 0 / 0
Регистрация: 09.06.2015
Сообщений: 12
15.07.2015, 14:26 259
Доброго всем времени суток!
Есть небольшая проблема с консольной графикой. Например, вместо символа "закрашенный прямоугольник", который соответствует '\xDB', выводит символ "Û". Возможно, кто-то знает решение (программа - последний пример из 10 главы).
horse.cpp

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
//horse.cpp
//модель лошадиных скачек
#include "msoftcon.h"    //for console graphics
#include <iostream>      //for I/O
#include <cstdlib>       //for random()
#include <ctime>         //for time()
using namespace std;
const int CPF = 5;       //columns per furlong
const int maxHorses = 7;  //maximum number of horses
class track;             //for forward references
//////////////////////////////////////
class horse
{
private:
    const track *ptrTrack;    //pointer to track
    const int horse_number;   //this horse's number
    float finish_time;        //this horse's finish time
    float distance_run;       //distance run so far
public:                      //create the horse
    horse(const int n, const track *ptrT) : 
        horse_number(n), ptrTrack(ptrT),
        distance_run(0.0)      //haven't moved yet
    {}
    ~horse()                  //destroy the horse
    {}
    void display_horse(const float elapsed_time);  //display the horse
}; //end class horse
//////////////////////////////////////////////////////////
class track
{
private:
    horse *hArray[maxHorses];      //array of ptrs-to-horses
    int total_horses;              //total number of horses
    int horse_count;             //horses created so far
    const float track_length;    //track length in furlongs
    float elapsed_time;          //time since start of race
public:
    track(float lenT, int nH);  //2-arg constructor
    ~track();                   //destructor
    void display_track();       //display track
    void run();                 //run the race
    float get_track_len() const; //return total track length
};     //end class track
//-------------------------------------------
void horse::display_horse(float elapsed_time)  //for each horse
{                                             //display horse & number
    set_cursor_pos(1 + int(distance_run * CPF),
        2 + horse_number * 2);
    set_color(static_cast<color>(cBLUE + horse_number));//horse 0 is blue
    char horse_char = '0' + static_cast<char>(horse_number);//draw horse
    _putch(' '); _putch('\xDB'); _putch(horse_char); _putch('\xDB');
                                                //until finish
    if (distance_run < ptrTrack->get_track_len() + 1.0 / CPF)
    {
        if (rand() % 3)        //skip about 1 of 3 ticks
            distance_run += 0.2F;  //advance 0.2 furlongs
        finish_time = elapsed_time;  //update finish time
    }
    else
    {                                     //display finish time
        int mins = int(finish_time) / 60;
        int secs = int(finish_time) - mins * 60;
        cout << " Time=" << mins << ":" << secs;
    }
}       //end display_horse()
//----------------------------------------------------------------
track::track(float lenT, int nH) :     //track constructor
track_length(lenT), total_horses(nH),
horse_count(0), elapsed_time(0.0)
{
    init_graphics();       //start graphics
    total_horses =         //not more than 7 horses
        (total_horses > maxHorses) ? maxHorses : total_horses;
    for (int j = 0; j < total_horses; j++) //make each horse
        hArray[j] = new horse(horse_count++, this);
 
    time_t aTime;                 //initialize random numbers
    srand(static_cast<unsigned>(time(&aTime)));
    display_track();
}   //end track constructor
//------------------------------------------------------------------
track::~track()               //track destructor
{
    for (int j = 0; j < total_horses; j++)  //delete each horse
        delete hArray[j];
}
//-------------------------------------------------------------------
void track::display_track()
{
    clear_screen();          //clear screen
                             //display track
    for (int f = 0; f <= track_length; f++)   //for each furlong
        for (int r = 1; r <= total_horses * 2 + 1; r++) //and screen row
        {
            set_cursor_pos(f * CPF + 5, r);
            if (f == 0 || f == track_length)
                cout << '\xDE';           //draw start or finish line
            else
                cout << '\xB3';          //draw furlong marker
        }
}            //end display_track()
//---------------------------------------------------------------
void track::run()
{
    while (!_kbhit())
    {
        elapsed_time += 1.75;     //update time
                                  //update each horse
        for (int j = 0; j < total_horses; j++)
            hArray[j]->display_horse(elapsed_time);
        wait(500);
    }
    _getch();                     //eat the keystroke
    cout << endl;
}
//---------------------------------------------------------------
float track::get_track_len() const
{
    return track_length;
}
//////////////////////////////////////////////
int main()
{
    float length;
    int total;
                                      //get data from user
    cout << "\nEnter track length (furlongs; 1 to 12): ";
    cin >> length;
    cout << "\nEnter number of horses (1 to 7): ";
    cin >> total;
    track theTrack(length, total);   //create the track
    theTrack.run();                  //run the race
 
    return 0;
}     //end main()

msoftcon.cpp
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
//msoftcon.cpp
//provides routines to access Windows console functions
 
//compiler needs to be able to find this file
//in MCV++, /Tools/Options/Directories/Include/type path name
 
#include "msoftcon.h"
HANDLE hConsole;         //console handle
char fill_char;          //character used for fill
//--------------------------------------------------------------
void init_graphics()
   {
   COORD console_size = {80, 25};
   //open i/o channel to console screen
   hConsole = CreateFile(L"CONOUT$", GENERIC_WRITE | GENERIC_READ,
                   FILE_SHARE_READ | FILE_SHARE_WRITE,
                   0L, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0L);
   //set to 80x25 screen size
   SetConsoleScreenBufferSize(hConsole, console_size);
   //set text to white on black
   SetConsoleTextAttribute( hConsole, (WORD)((0 << 4) | 15) );
 
   fill_char = '\xDB';  //default fill is solid block
   clear_screen();
   }
//--------------------------------------------------------------
void set_color(color foreground, color background)
   {
   SetConsoleTextAttribute( hConsole, 
                        (WORD)((background << 4) | foreground) );
   }  //end setcolor()
 
/* 0  Black          8  Dark gray
   1  Dark blue      9  Blue
   2  Dark green     10 Green
   3  Dark cyan      11 Cyan
   4  Dark red       12 Red
   5  Dark magenta   13 Magenta
   6  Brown          14 Yellow
   7  Light gray     15 White
*/
//--------------------------------------------------------------
void set_cursor_pos(int x, int y)
   {
   COORD cursor_pos;              //origin in upper left corner
   cursor_pos.X = x - 1;          //Windows starts at (0, 0)
   cursor_pos.Y = y - 1;          //we start at (1, 1)
   SetConsoleCursorPosition(hConsole, cursor_pos);
   }
//--------------------------------------------------------------
void clear_screen()
   {
   set_cursor_pos(1, 25);
   for(int j=0; j<25; j++)
      _putch('\n');
   set_cursor_pos(1, 1);
   }
//--------------------------------------------------------------
void wait(int milliseconds)
   {
   Sleep(milliseconds);
   }
//--------------------------------------------------------------
void clear_line()                    //clear to end of line
   {                                 //80 spaces
   //.....1234567890123456789012345678901234567890
   //.....0........1.........2.........3.........4 
   _cputs("                                        ");
   _cputs("                                        ");
   }
//--------------------------------------------------------------
void draw_rectangle(int left, int top, int right, int bottom) 
   {
   char temp[80];
   int width = right - left + 1;
 
   int j;
   for(j = 0; j<width; j++)      //string of squares
      temp[j] = fill_char;
   temp[j] = 0;                      //null
 
   for(int y=top; y<=bottom; y++)  //stack of strings 
      {
      set_cursor_pos(left, y);
      _cputs(temp);
      }
   }
//--------------------------------------------------------------
void draw_circle(int xC, int yC, int radius)
   {
   double theta, increment, xF, pi=3.14159;
   int x, xN, yN;
 
   increment = 0.8 / static_cast<double>(radius);
   for(theta=0; theta<=pi/2; theta+=increment)  //quarter circle
      {
      xF = radius * cos(theta);  
      xN = static_cast<int>(xF * 2 / 1); //pixels not square
      yN = static_cast<int>(radius * sin(theta) + 0.5);
      x = xC-xN;
      while(x <= xC+xN)          //fill two horizontal lines
         {                       //one for each half circle
         set_cursor_pos(x,   yC-yN); _putch(fill_char);  //top
         set_cursor_pos(x++, yC+yN); _putch(fill_char);  //bottom
         }
      }  //end for
   }
//--------------------------------------------------------------
void draw_line(int x1, int y1, int x2, int y2)
   {
 
   int w, z, t, w1, w2, z1, z2;
   double xDelta=x1-x2, yDelta=y1-y2, slope;
   bool isMoreHoriz;
 
   if( fabs(xDelta) > fabs(yDelta) ) //more horizontal
      {
      isMoreHoriz = true;
      slope = yDelta / xDelta;
      w1=x1; z1=y1; w2=x2, z2=y2;    //w=x, z=y 
      }
   else                              //more vertical
      {
      isMoreHoriz = false;
      slope = xDelta / yDelta;
      w1=y1; z1=x1; w2=y2, z2=x2;    //w=y, z=x
      }
 
   if(w1 > w2)                       //if backwards w
      {
      t=w1; w1=w2; w2=t;             //   swap (w1,z1)
      t=z1; z1=z2; z2=t;             //   with (w2,z2)
      }
   for(w=w1; w<=w2; w++)            
      {
      z = static_cast<int>(z1 + slope * (w-w1));
      if( !(w==80 && z==25) )        //avoid scroll at 80,25
         {
         if(isMoreHoriz)
            set_cursor_pos(w, z);
         else
            set_cursor_pos(z, w);
         _putch(fill_char);
         }
      }
   }
//--------------------------------------------------------------
void draw_pyramid(int x1, int y1, int height)
   {
   int x, y;
   for(y=y1; y<y1+height; y++)
      {
      int incr = y - y1;
      for(x=x1-incr; x<=x1+incr; x++)
         {
         set_cursor_pos(x, y);
         _putch(fill_char);
         }
      }
   }
//--------------------------------------------------------------
void set_fill_style(fstyle fs)
   {
   switch(fs)
      {
      case SOLID_FILL:  fill_char = '\xDB'; break;
      case DARK_FILL:   fill_char = '\xB0'; break;
      case MEDIUM_FILL: fill_char = '\xB1'; break;
      case LIGHT_FILL:  fill_char = '\xB2'; break;
      case X_FILL:      fill_char = 'X';    break;
      case O_FILL:      fill_char = 'O';    break;
      }
   }
//--------------------------------------------------------------

msoftcon.h
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
//msoftcon.h
//declarations for Lafore's console graphics functions
//uses Window's console functions
 
#ifndef _INC_WCONSOLE    //don't let this file be included
#define _INC_WCONSOLE    //twice in the same source file
 
#include <windows.h>     //for Windows console functions
#include <conio.h>       //for kbhit(), getche()
#include <math.h>        //for sin, cos
 
enum fstyle { SOLID_FILL, X_FILL,      O_FILL, 
              LIGHT_FILL, MEDIUM_FILL, DARK_FILL };
 
enum color {
   cBLACK=0,     cDARK_BLUE=1,    cDARK_GREEN=2, cDARK_CYAN=3, 
   cDARK_RED=4,  cDARK_MAGENTA=5, cBROWN=6,      cLIGHT_GRAY=7,
   cDARK_GRAY=8, cBLUE=9,         cGREEN=10,     cCYAN=11, 
   cRED=12,      cMAGENTA=13,     cYELLOW=14,    cWHITE=15 };
//--------------------------------------------------------------
void init_graphics();
void set_color(color fg, color bg = cBLACK);
void set_cursor_pos(int x, int y);
void clear_screen();
void wait(int milliseconds);
void clear_line();
void draw_rectangle(int left, int top, int right, int bottom);                    
void draw_circle(int x, int y, int rad);
void draw_line(int x1, int y1, int x2, int y2);
void draw_pyramid(int x1, int y1, int height);
void set_fill_style(fstyle);
#endif /* _INC_WCONSOLE */

Решение всех упражнений из книги Р. Лафоре "Объектно-ориентированное программирование в С++"
0
369 / 310 / 65
Регистрация: 14.10.2014
Сообщений: 1,318
16.07.2015, 14:57 260
Да решение тут примитивное - нужно найти необходимый код нужного символа в нужной кодировке - в общем я проверил Windows-1251, смотрел кодировку в википедии к сожалению закрашенного прямоугольника там нет, но я попробовал другой символ - § '\xA7' - всё прекрасно работает.


У меня кстати прога работает только если в msoftcon.cpp в 15 строке:

C++
1
2
3
hConsole = CreateFile(L"CONOUT$", GENERIC_WRITE | GENERIC_READ,
                   FILE_SHARE_READ | FILE_SHARE_WRITE,
                   0L, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0L);
убрать символ L

C++
1
hConsole = CreateFile("CONOUT$", GENERIC_WRITE | GENERIC_READ,
Миниатюры
Решение всех упражнений из книги Р. Лафоре "Объектно-ориентированное программирование в С++"  
0
16.07.2015, 14:57
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
16.07.2015, 14:57
Помогаю со студенческими работами здесь

Ошибки в книги Р.Лафоре "Объектно-Ориентирование программирование в C++"
Добрый день всем присутствующим. Хотелось бы обсудить книгу Robert Lafore Object-Oriented...

Ориентированное программирование в С++ Р. Лафоре
Доброго времени суток форумчане! Хочу вот закинуть себе книгу &quot;Объектно-ориентированное...

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

Объектно-ориентированное программирование
Друзья, прошу помощи, накопил кучу долгов по учёбе, совершенно нет времени разобраться с задачами,...

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

Объектно-ориентированное программирование
Добрый вечер, помогите пожалуйста написать программу) Класс прямая(y=ax+b),члены класса...

Объектно-ориентированное программирование
Составить программу для игры в шахматы. Каждая уникальная шахматная фигура выступает в качестве...


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

Или воспользуйтесь поиском по форуму:
260
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru