0 / 0 / 0
Регистрация: 05.02.2019
Сообщений: 19
1

Не могу понять почему вылетает программа

05.02.2019, 14:36. Показов 570. Ответов 6

Студворк — интернет-сервис помощи студентам
Здравствуйте, у меня по каким то причинам вылетает программа, вроде всё правильно, подскажите пожалуйста где я ошибся и почему вылетает программа?

C++ (Qt)
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
#include <iostream>
#include <iomanip>
#include <cstring>
 
using namespace std;
 
class Student {
private:
    char name[51];
    char surname[51];
    int hp;
    int energy;
    int iq;
    int sanity;
    int excitement;
 
    void change_field(int &field, int delta);
    void change_params(int hp, int energy, int iq, int sanity, int excitement);
public:
    Student();
    Student(char *name[51], char *surname[51]);
    bool is_alive();
    void show();
    void eat();
    void wait();
    void study();
    void sleep();
    void watch_tv();
};
 
int main()
{
    char name[50], surname[50];
    cin >> name >> surname;
    Student stud(name, surname);
    int n;
    cin >> n;
    for (int i = 0; i < n; ++i) {
        char com[9];
        cin >> com;
        if (strcmp(com, "Wait") == 0) {
            stud.wait();
        } else if (strcmp(com, "Eat") == 0) {
            stud.eat();
        } else if (strcmp(com, "Study") == 0) {
            stud.study();
        } else if (strcmp(com, "Sleep") == 0) {
            stud.sleep();
        } else if (strcmp(com, "Watch") == 0) {
            cin >> com;
            stud.watch_tv();
        } else return 1;
        stud.show();
    }
    return 0;
}
 
Student::Student() {
//    cin >> this -> name >> this -> surname;
    this -> hp = 100;
    this -> energy = 100;
    this -> iq = 20;
    this -> sanity = 100;
    this -> excitement = 50;
}
 
Student::Student(char *name[50], char *surname[50]) {
    strncpy(this -> name, *name, 51);
    strncpy(this -> surname, *surname, 51);
    Student();
    delete [] name;
    delete [] surname;
}
 
bool Student::is_alive() {
    return this -> hp > 0;
}
 
void Student::show() {
    cout <<this -> name << " " << this -> surname
         << ": HP = " << setw(3) << setfill('0') <<  this -> hp << ", "
         << "Energy = " << setw(3) << setfill('0') << this -> energy << ", "
         << "IQ = " << setw(3) << setfill('0') << this -> iq << ", "
         << "Sanity = " << setw(3) << setfill('0') << this -> sanity << ", "
         << "Excitement = " << setw(3) << setfill('0') << this -> excitement << ".";
    if (this -> is_alive() == false)
        cout << " Game over.";
    cout << endl;
}
 
void Student::change_field(int &field, int delta) {
    field += delta;
    field = field > 100 ? 100 : field;
    field = field < 0 ? 0 : field;
}
 
void Student::change_params(int hp, int energy, int iq, int sanity, int excitement) {
        this -> change_field(this -> energy, energy);
        this -> change_field(this -> hp, hp);
        this -> change_field(this -> iq, iq);
        this -> change_field(this -> sanity, sanity);
        this -> change_field(this -> excitement, excitement);
}
 
void Student::eat() {
    int hpP = 1, energyP = 7, iqP = -1, sanityP = 0, excitementP = -2;
    if (!is_alive()) return;
    change_params(hpP, energyP, iqP, sanityP, excitementP);
}
 
void Student::wait() {
    int energyP = -3, hpP = 1, iqP = 0, sanityP = 0, excitementP = -3;
    if (!is_alive()) return;
    change_params(hpP, energyP, iqP, sanityP, excitementP);
}
 
void Student::study() {
    int energyP = -4, hpP = -2, iqP = 5, sanityP = -5, excitementP = -2;
    if (!is_alive()) return;
    change_params(hpP, energyP, iqP, sanityP, excitementP);
}
 
void Student::sleep() {
    int energyP = -2, hpP = 2, iqP = 0, sanityP = 7, excitementP = 0;
    if (!is_alive()) return;
    change_params(hpP, energyP, iqP, sanityP, excitementP);
}
 
void Student::watch_tv() {
    int energyP = -3, hpP = -2, iqP = -3, sanityP = 1, excitementP = 5;
    if (!is_alive()) return;
    change_params(hpP, energyP, iqP, sanityP, excitementP);
}
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
05.02.2019, 14:36
Ответы с готовыми решениями:

Программа на С++ вылетает, не могу понять почему!?
#include &lt;iostream&gt; #include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include &lt;allegro.h&gt; #include...

Не могу понять почему программа не выводит результат (простейшая программа)
Здравствуйте уважаемые форумчане! Я начал изучать C++ при помощи книги. На днях я столкнулся со...

Не могу понять почему не работает программа
int f,x,a,b,c; cin&gt;&gt;x; if (x&gt;0) {f=pow(-x,4); cout&lt;&lt;f;} else {f=x+92; cout&lt;&lt;f;} if...

не могу понять почему не работает программа
#include &lt;iostream&gt; #include &lt;conio.h&gt; #include &lt;clocale&gt; #include &lt;cmath&gt; using namespace std;...

6
277 / 226 / 93
Регистрация: 27.06.2016
Сообщений: 639
05.02.2019, 15:44 2
Aleks00231, в конструкторе student применяете delete к аргументам name и surname, хотя они не выделены в динамической памяти. И что это за массивы в параметрах и как оно вообще компилится я не знаю.

Добавлено через 4 минуты
Aleks00231,
main.cpp:21:5: note: no known conversion for argument 1 from ‘char [50]’ to ‘char**’
0
24 / 21 / 3
Регистрация: 04.11.2014
Сообщений: 283
05.02.2019, 15:51 3
Массивы так не передаются:
C++
1
Student(char *name[51], char *surname[51]);
Надо передавать указатель на массив и его длину:
C++
1
Student(char *name, char *surname, int len);
Да и в принципе не так объявляются строки, у вас массив из символов выходит, для строки вот так:
C++
1
    char* name = new char[50];
В этом случае длину передавать не надо
0
Mental handicap
1245 / 623 / 171
Регистрация: 24.11.2015
Сообщений: 2,429
05.02.2019, 16:05 4
Цитата Сообщение от ЗеХель Посмотреть сообщение
Да и в принципе не так объявляются строки, у вас массив из символов выходит, для строки вот так
Сильное заявление.
0
24 / 21 / 3
Регистрация: 04.11.2014
Сообщений: 283
05.02.2019, 16:07 5
Azazel-San, я завтыкал, и то верно, все норм там
0
Mental handicap
1245 / 623 / 171
Регистрация: 24.11.2015
Сообщений: 2,429
05.02.2019, 16:09 6
ЗеХель, с каких пор это char name[50] - массив символов, а это char* name = new char[50] - строка?
0
24 / 21 / 3
Регистрация: 04.11.2014
Сообщений: 283
05.02.2019, 16:11 7
Azazel-San, я уже исправил своё сообщение, говорю же завтыкал чутка
0
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
05.02.2019, 16:11
Помогаю со студенческими работами здесь

Не могу понять, почему программа выводит нули
#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;math.h&gt; #include &lt;locale.h&gt; double rnd();...

Не могу понять почему программа работает не правильно!
Задание: Программа находит в строке 1 символ который не входит во 2 заданную строку. Помогите...

Не могу понять, почему программа неправильно работает!
Изучаю С++ по Страуструпу Б. - Программирование. Принципы и практика использования C++. Есть...

не могу понять почему не работет программа. Где ошибка?
#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;ctime&gt; #include &lt;windows.h&gt; using namespace...


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

Или воспользуйтесь поиском по форуму:
7
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2023, CyberForum.ru