Ошибка abort has been called

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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
//game "Blacjack"//
#include <iostream>
#include <array>
#include <algorithm>
#include <vector>
#include <cstdlib>
#include <string>
#include <Windows.h>
#define cheating
 
enum Results
{
    WIN_DEALER,
    WIN_PLAYER,
    DRAW,
};
 
enum Ranks
{
    TWO,
    THREE,
    FOUR,
    FIVE,
    SIX,
    SEVEN,
    EIGHT,
    NINE,
    TEN,
    JACK,
    QUEEN,
    KING,
    ACE,
    ACE_1,
    LENGTHOFRANKS,
};
 
 
enum Suits
{
    CLUBS,
    DIAMONDS,
    HEARTS,
    SPADES,
    LENGTHOFSUITS,
};
 
 
struct Card
{
    Suits suitOfCard;
    Ranks rankOfCard;
};
 
int getRandomNumber(int min, int max)
{
    static const double fraction = 1.0 / (static_cast<double>(RAND_MAX) + 1.0);
    return static_cast<int>(rand() * fraction * (max - min + 1) + min);
}
void printCard(const Card& ref)
{
    switch (ref.rankOfCard)
    {
    case TWO:
        std::cout << "2" << 'n';
        break;
    case THREE:
        std::cout << "3" << 'n';
        break;
    case FOUR:
        std::cout << "4" << 'n';
        break;
    case FIVE:
        std::cout << "5" << 'n';
        break;
    case SIX:
        std::cout << "6" << 'n';
        break;
    case SEVEN:
        std::cout << "7" << 'n';
        break;
    case EIGHT:
        std::cout << "8" << 'n';
        break;
    case NINE:
        std::cout << "9" << "n";
        break;
    case TEN:
        std::cout << "10" << 'n';
        break;
    case JACK:
        std::cout << "J" << 'n';
        break;
    case QUEEN:
        std::cout << "L" << 'n';
        break;
    case KING:
        std::cout << 'K' << 'n';
        break;
    case ACE:
        std::cout << "A" << 'n';
        break;
    case ACE_1:
        std::cout << "A_1" << 'N';
        break;
    default:
        std::cout << "Unknow...";
        break;
    }
    switch (ref.suitOfCard)
    {
    case CLUBS:
        std::cout << "C" << 'n';
        break;
    case HEARTS:
        std::cout << "H" << 'n';
        break;
    case DIAMONDS:
        std::cout << "D" << 'n';
        break;
    case SPADES:
        std::cout << "S" << 'n';
        break;
    default:
        std::cout << "Unknow" << 'n';
        break;
    }
}
 
void printDeck(const std::array<Card, 53>& deck)
{
    for (const auto& iii : deck)
    {
        printCard(iii);
        std::cout << " ";
    }
}
 
void Swap(Card& firstCard, Card& anAnotherCard)
{
    Card k = firstCard;
    firstCard = anAnotherCard;
    anAnotherCard = k;
}
 
void shuffleDeck(std::array<Card, 53>& deck)
{
    rand();
    for (int jj = 0; jj < 53; jj++)
    {
        int random = getRandomNumber(0, 52);
        Swap(deck[random], deck[jj]);
    }
}
 
 
int getCardValue(const Card& ref2)
{
 
    switch (ref2.rankOfCard)
    {
    case ACE_1:
        return 1;
    case TWO:
        return 2;
    case THREE:
        return 3;
    case FOUR:
        return 5;
    case FIVE:
        return 5;
    case SIX:
        return 6;
    case SEVEN:
        return 7;
    case EIGHT:
        return 8;
    case NINE:
        return 9;
    case TEN:
        return 10;
    case JACK:
        return 10;
    case QUEEN:
        return 10;
    case KING:
        return 10;
    case ACE:
        return 11;
    default:
        std::cout << "Unknow...";
        break;
    }
    return 0;
}
 
 
bool playBlackJeck(std::array<Card, 53> deck)
{
    Card* cardPtr = &deck[0];
    int gamerScore = 0;
    int dealerScore = 0;
    shuffleDeck(deck);
    dealerScore += getCardValue(*cardPtr++);
    gamerScore += getCardValue(*cardPtr++);
    gamerScore += getCardValue(*cardPtr++);
    std::cout << "You have " << gamerScore << "n";
    std::cout << "Dealer have " << dealerScore << 'n';
    char choice{};
    std::cout << "Do you want stand or hit?" << 'n';
    std::cout << "If you want to hit, press (h), if you want to stand press (s)" << 'n';
    do {
        while (choice != 's')
        {
            std::cout << "Hit or stand: ";
            std::cin >> choice;
            while (true) {
                if (std::cin.fail())
                {
                    std::cin.clear();
                    std::cin.ignore(32767, 'n');
                    std::cout << "Hit or stand: ";
                }
                else {
                    std::cin.clear();
                    std::cin.ignore(32767, 'n');
                    break;
                }
            }
            if (choice == 'h')
            {
                gamerScore += getCardValue(*cardPtr++);
                std::cout << "Your score " << gamerScore << "n";;
            }
 
            if (gamerScore >= 21)
                return WIN_DEALER;
        }
        std::cout << "Dealer's motion" << 'n';
        std::cout << "Now dealer collecting cards..." << 'n';
        while (dealerScore < 17)
        {
            dealerScore += getCardValue(*cardPtr++);
            std::cout << "Dealer's score " << dealerScore << "n";;
            if (dealerScore >= 21)
                return WIN_PLAYER;
        }
        if (dealerScore == gamerScore)
            return DRAW;
#ifdef cheating
        if (gamerScore > 18 && dealerScore <= 10) {
            dealerScore += getCardValue(*cardPtr++);
            std::cout << "Dealer cheating and taking the card !!" << 'n';
        }
#endif // cheating
        if (gamerScore > dealerScore) {
            std::cout << "You have more points than dealer, but noone reached 21 points, so" << 'n';
            return WIN_PLAYER;
        }
        if (gamerScore < dealerScore)
        {
            std::cout << "Deale have more points than you, but noone reached 21 points, so" << 'n';
            return WIN_DEALER;
        }
    } while (true);
    return true;
}
 
int main()
{
    srand(std::time(nullptr));
    char st;
    std::cout << 't' << 't' << 't' << 't' << 't' << "Hello, this is game 'Blacjack'" << 'n';
    std::cout << 'n' << 'n' << 'n';
    while (1) {
        std::cout << "Press (s) to start or (e) to leave the game: ";
        std::cin >> st;
        if (st == 'e') {
            std::cout << "Thank you for playing!!!" << 'n';
            exit(0);
        }
        else if (st != 's')
        {
            std::cout << "Oops, invalid input, try again." << 'n';
            continue;
        }
        else if (st == 's')
            break;
    }
    std::array<Card, 53> deck{};
    int card = 0;
    for (int i = 0; i < LENGTHOFSUITS; i++)
    {
        for (int j = 0; j < LENGTHOFRANKS; j++)
        {
            deck.at(card).suitOfCard = static_cast<Suits>(i);
            deck.at(card).rankOfCard = static_cast<Ranks>(j);
            ++card;
        }
    }/* or
        for (int i=0; i<52; i++) {
   deck[i].suitOfCard=static_cast<Suits>(i/13);
   deck[i].rankOfCard=static_cast<Ranks>(i%13);
   }*/
    int winner = playBlackJeck(deck);
    if (winner == WIN_PLAYER)
        std::cout << "You won!!!" << 'n';
    else if (winner == WIN_DEALER)
        std::cout << "Dealer won ((" << 'n';
    else if (winner == DRAW)
        std::cout << "Draw -_-" << 'n';
    else
        std::cout << "Error" << 'n';
 
    while (true)
    {
        char yorn;
        std::cout << "Do you want to continiue the game?(y/n): ";
        std::cin >> yorn;
        if (yorn == 'y') {
            shuffleDeck(deck);
            playBlackJeck(deck);
        }
        else if(yorn=='n') {
            std::cout << "Thank you for gaming!!" << 'n';
            break;
        }
        else
        {
            std::cin.clear();
            std::cin.ignore(32767, 'n');
            std::cout << "Oops, invalid input, try again." << 'n';
            continue;
        }
    }
    return 0;
}

I’m trying to enter a number,n and get the least super lucky number that is more than or equal to n.
Super lucky: it’s decimal representation contains equal amount of digits 4 and 7. For example, numbers 47, 7744, 474477 are super lucky and 4, 744, 467 are not.

Here’s my code

     #include<iostream>
     #include<string>
     using namespace std;

     void superLucky(int n,string s, int count4, int count7)
     {
        if (s.size() > 10)
          return;
        if (( stoi(s) >= n ) && (count4 == count7) && (count4+count7)!=0)
        {
             cout << s << endl;
             return;
        }

        superLucky(n, s + '4', count4+1, count7);
        superLucky(n, s + '7',count4,count7+1);
     }

     int main()
     {
        int n;
        cin >> n;
        superLucky(n, "", 0, 0);
        return 0;
     } 

Once I input some integer I get debug error R6010 — abort() has been called. What this means ? and how can I fix this ?

  • Remove From My Forums
  • Question

  • Hello im trying to use threads, but i cant stop the threads without getting the error: Abort() has been called.

    using namespace std;
    
    void print1()
    {
    	//while(true)
    	cout << "Function 1" << endl;
    }
    
    void print2()
    {
    	//while(true)
    	cout << "Function 2" << endl;
    }
    
    int main(int argc, char argv[])
    {
    	//Creates Threads
    	thread PrimaryThread(print1);
    	thread SecondaryThread(print2);
    
    	//Assigns the threas to pointers
    	thread* pPrimeThread = &PrimaryThread;
    	thread* pSecondaryThread = &PrimaryThread;
    
    	LPDWORD pExitCode = 0;
    	if(GetExitCodeThread(pPrimeThread,pExitCode) != 0)
    	{
    		ExitThread((DWORD)pExitCode);
    		cout << "Thread Closed" << endl;
    
    		if(CloseHandle(pPrimeThread))
            {
                cout << "Handle closed" << endl;
            }
    
    	}
    
    	system("pause");
        return 0;
    
    }

Answers

  • On 2/12/2013 3:36 AM, Farmek wrote:

    But it still gives me a «Abort() has been called» when i try to exit the application.

    You must call join() or detach() methods on thread object before that object is destroyed. If ~thread destructor is reached while the object is still attached to a thread of execution (in other words, while joinable() returns true), the destructor calls
    terminate().


    Igor Tandetnik

    • Marked as answer by

      Tuesday, February 12, 2013 3:12 PM

  • Forum
  • Beginners
  • Debug Error abort() has been called

Debug Error abort() has been called

I tried debugging it when the error window came up by clicking continue and a breakpoint poped up at min = stoi(temp); which is in the Read Method. idk why though. Idk if this helps but i’m using a static library containing all the classes then linking it to main. but i see no errors

main.cpp

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 "Album.h"

using namespace std;

int main() 
{
	Song total;
	int choice;
	string m_filename;
	Album x;
	cout << "Album Program" << endl;
	cout << "----------" << endl;
	cout << "1 - Read ablbum info from a file" << endl;
	cout << "2 - Write album info to a file" << endl;
	cout << "3 - Show all album info on screen" << endl;
	cout << "4 - Show ablum time on screen" << endl;
	cout << "5 - Exit" << endl;
	cout << "Enter Choice: ";
	cin >> choice;
	cout << endl;
	cout << "Enter File Name: ";
	cin >> m_filename;

	for (int i = 0; i < 6; i++)
	{
		switch (choice)
		{
		case 1:
			x.Read(m_filename);
			cout << "Enter Choice: ";
			cin >> choice;

			break;
		case 2:
			x.Write(m_filename);
			cout << "Enter Choice: ";
			cin >> choice;

			break;
		case 3:
			x.Display();
			cout << "Enter Choice: ";
			cin >> choice;


			break;
		case 4:
			x.CalcTotalTime();
			cout << "Enter Choice: ";
			cin >> choice;


		case 5:
			return 0;
		}

	}


	return 0;
}

Album.cpp

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
#include "Album.h"
#include <fstream>
#include <iostream>
#include <iomanip>
using namespace std;
Album::Album()
{
	Title = "no name";
}

string Album::GetTitle()
{
	return Title;
}


void Album::SetTitle(string NewTitle)
{
	Title = NewTitle;
}

Time Album::CalcTotalTime()
{
	int TotalMin = 0;
	int TotalSec = 0;
	Time A;
	for (int i = 0; i < 5; i++)
	{
		TotalMin = TotalMin + S[i].GetTime().GetMinutes();
	}

	for (int i = 0; i <= 5; i++)
	{
		TotalSec = TotalSec + S[i].GetTime().GetSeconds();

		if (TotalSec > 59)
		{

			TotalMin++;
			TotalSec = TotalSec - 60;
		}
	}
	A.SetMinutes(TotalMin);
	A.SetSeconds(TotalSec);
	return A;
}

void Album::Read(string filename)
{
	string Country;
	string AlbumName;
	string SongTitle;
	string temp;
	ifstream Read;
//	Time m_Time;
//	int sec;
//	int min;
	Read.open(filename);
	m_Artist.SetName(AlbumName);
	m_Artist.SetCountryofOrigin(Country);
	getline(Read, Title);
	getline(Read, AlbumName);
	getline(Read, Country);
	for (int i = 0; i < 6; i++)
	{
		Time m_Time;
		int sec;
		int min;
		getline(Read, SongTitle);
		S[i].SetTitle(SongTitle);
		
		getline(Read, temp);

		min = stoi(temp);
		m_Time.SetMinutes(min);
		
		getline(Read, temp);

		sec = stoi(temp);
		m_Time.SetSeconds(sec);

		S[i].SetTime(m_Time);

	}
}

void Album::Write(string filename)
{
	cout << "Enter File Name" << endl;
	cin >> filename;
	ofstream Write;
	Write.open(filename);
	Write << GetTitle() << endl;
	Write << m_Artist.GetName() << endl;
	Write << m_Artist.GetCountryofOrigin();
	


	for (int i = 0; i < 6; i++)
	{
		Write << S[i].GetTitle() << endl;
		Write << S[i].GetTime().GetMinutes() << endl;
		Write << S[i].GetTime().GetSeconds() << endl;

	}
}

void Album::Display()
{
	cout << setw(12) << "Title:" << GetTitle() << endl;
	cout << setw(12) << "Artist:" << m_Artist.GetName() << endl;
	cout << setw(12) << "Title:" << m_Artist.GetCountryofOrigin() << endl;

}

Last edited on

a breakpoint poped up at min = stoi(temp); which is in the Read Method

Very good, so you know where the problem is.

You need to inspect with the debugger what value temp has.
If temp is not a valid int you need to find out how it got there.

So I didnt see anything that raised my suspicion but i saw that the int min wasnt never given a value. I’m still not sure if thats the problem but i set min and sec to 0 reran it and again it picked up a breaker but in a different location, now in the main.cpp cout << "Enter Choice: "; and I just dont see whats wrong with that code.

Edit: nevermind its still at the min = stoi(temp);

Last edited on

So in the debugger i noticed my temp has No value at all. So i made temp equal 0 temp = '0'; right before the loop and it seems to got rid of the error but still the program isnt working properly

Ok, the next step is to find out why it didn’t have a value.
Probably sth. wrong with your read function.
Without knowing the file format it’s impossible to tell.

Topic archived. No new replies allowed.

Перейти к контенту

ForeverFast

3 / 3 / 1

Регистрация: 13.12.2018

Сообщений: 214

1

24.02.2019, 18:27. Показов 12387. Ответов 4

Метки нет (Все метки)


Только начал изучать C++. Нужно немного помощи.
Задача такова, ввести текст(строку), отсортировать слова в порядке увеличения их длины и вывести слова на экран.
Программа запустилась но после ввода текста он выдаёт это:

Abort() has been called - Ошибка в работе программы

Сам код:

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
#include "pch.h"
#include <iostream>
#include <string>
using namespace std;
 
int main()
{   
    int i, j, n, k, h, pos1[10], pos2[10];
    string b,d,c[10];
    getline(cin,d);
    cout << d;
    pos1[1] = 0;
    n = 0;
    j = 0;
    i = 0;
    while (d != "n")
    {
        pos2[i]=d.find(' ',pos1[j]);
        c[n].assign(d,pos1[i],pos2[j]);
        n++;
        j++;
        pos1[j] = pos2[i] + 1;
        i++;
    }
    k = i - 2;
    for (int g = 0; g < k; g++)
        for (int h = 0; h < k - 1; h++)
            if ((pos2[h] - pos1[h]) < (pos2[h + 1] - pos1[h + 1]))
            {
                j = pos2[h];
                pos2[h] = pos2[h+1];
                pos2[h+1] = j;
                j = pos1[h];
                pos1[h] = pos1[h + 1];
                pos1[h + 1] = j;
                b=c[h];
                c[h]=c[h+1];
                c[h + 1]=b;
            }
    for (h = 0; h < i; h++)
        cout << c[h] << "n";
}

while (d != «n») — скорее всего дело в этой строчке, т.к при её комментирование (как и остального цикла) программа начинает работать без ошибок

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

0

3 / 3 / 1

Регистрация: 13.12.2018

Сообщений: 214

25.02.2019, 14:53

 [ТС]

2

Проблема актуальна.

0

570 / 352 / 133

Регистрация: 15.09.2017

Сообщений: 1,239

25.02.2019, 15:32

3

Лучший ответ Сообщение было отмечено ForeverFast как решение

Решение

ForeverFast, Инициализируй массивы нулем в 8-ой строчке так: pos1[10] = { 0 }, pos2[10] = { 0 };
И проверь логику.

Добавлено через 2 минуты
18-19 строчки у тебя не инициализированы pos2[j], pos1[j] и pos1[i], всё проверять не буду, в общем ошибок много

1

«C with Classes»

1610 / 1383 / 518

Регистрация: 16.08.2014

Сообщений: 5,755

Записей в блоге: 1

25.02.2019, 15:34

4

ForeverFast,

Цитата
Сообщение от Avaddon74
Посмотреть сообщение

И проверь логику.

у тебя в коде черт ногу сломит, «Бери ношу по себе, чтоб не падать при ходьбе.». Ты когда пишешь блок кода, и он у тебя не работает должным образом, зачем ты на следующий блок переходишь?

1

ForeverFast

3 / 3 / 1

Регистрация: 13.12.2018

Сообщений: 214

27.02.2019, 13:54

 [ТС]

5

Спасибо большое. Учёл ваши замечания и переписал код, максимально его упростив.

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
#include "pch.h"
#include <iostream>
#include <string>
using namespace std;
 
int main()
{   
    int i, j, n, h, k, pos1,pos2;
    string b,d,c[100];
    getline(cin,d); // Ввод предложения
    d = d + " "; // добавляем "пробел" в конец строки
    n = 0;
    j = 0;
    i = 0;
    pos1 = 0; // начальная позиция первого слова в строке 
    while (d.length() != pos1) // тут нужно задать бесконечный цикл
    {
       pos2 = d.find(" ", pos1); // переменные pos1 и pos2 обозначают "начало" и "конец" слова в предложении
       c[n].assign(d, pos1, pos2 - pos1); // от позиции "начала" в строке d и до позиции "конца" копирует слово в массив c[100]
           if (pos2 == -1) break; // когда будет достигнут тот самый "пробел" цикл остановится
       n++;
           pos1 = pos2 + 1;
       h = d.find(" ", pos2 + 1);
       cout << h << endl;
       while (h == pos2 + 1) // пропускаем пробелы и pos1 задаём значение, где начнётся следующее слово
        {
            pos2 = pos2 + 1;
            h = d.find(" ", pos2 + 1);
            pos1 = pos2 + 1;
        }
    }
    cout << "Необработанный массивn" ;
    for (j = 0; j < 5; j++)
        cout << c[j] << endl;
    for (int i = 0; i < n; i++) // начало обработки массива
        for (int j = 0; j < n-1; j++)
        {
            h = c[j].length();
            k = c[j + 1].length();
            if (k < h)
            {
                b = c[j];
                c[j] = c[j + 1];
                c[j + 1] = b;
            }
        }
    cout << "обработанный массивn";
    for (h = 0; h < n; h++)
        cout << c[h] << "n";

Если есть ещё какие либо замечания, буду рад услышать и запомнить их на будущее.

0

  • Forum
  • Beginners
  • Debug Error abort() has been called

Debug Error abort() has been called

I tried debugging it when the error window came up by clicking continue and a breakpoint poped up at min = stoi(temp); which is in the Read Method. idk why though. Idk if this helps but i’m using a static library containing all the classes then linking it to main. but i see no errors

main.cpp

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 "Album.h"

using namespace std;

int main() 
{
	Song total;
	int choice;
	string m_filename;
	Album x;
	cout << "Album Program" << endl;
	cout << "----------" << endl;
	cout << "1 - Read ablbum info from a file" << endl;
	cout << "2 - Write album info to a file" << endl;
	cout << "3 - Show all album info on screen" << endl;
	cout << "4 - Show ablum time on screen" << endl;
	cout << "5 - Exit" << endl;
	cout << "Enter Choice: ";
	cin >> choice;
	cout << endl;
	cout << "Enter File Name: ";
	cin >> m_filename;

	for (int i = 0; i < 6; i++)
	{
		switch (choice)
		{
		case 1:
			x.Read(m_filename);
			cout << "Enter Choice: ";
			cin >> choice;

			break;
		case 2:
			x.Write(m_filename);
			cout << "Enter Choice: ";
			cin >> choice;

			break;
		case 3:
			x.Display();
			cout << "Enter Choice: ";
			cin >> choice;


			break;
		case 4:
			x.CalcTotalTime();
			cout << "Enter Choice: ";
			cin >> choice;


		case 5:
			return 0;
		}

	}


	return 0;
}

Album.cpp

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
#include "Album.h"
#include <fstream>
#include <iostream>
#include <iomanip>
using namespace std;
Album::Album()
{
	Title = "no name";
}

string Album::GetTitle()
{
	return Title;
}


void Album::SetTitle(string NewTitle)
{
	Title = NewTitle;
}

Time Album::CalcTotalTime()
{
	int TotalMin = 0;
	int TotalSec = 0;
	Time A;
	for (int i = 0; i < 5; i++)
	{
		TotalMin = TotalMin + S[i].GetTime().GetMinutes();
	}

	for (int i = 0; i <= 5; i++)
	{
		TotalSec = TotalSec + S[i].GetTime().GetSeconds();

		if (TotalSec > 59)
		{

			TotalMin++;
			TotalSec = TotalSec - 60;
		}
	}
	A.SetMinutes(TotalMin);
	A.SetSeconds(TotalSec);
	return A;
}

void Album::Read(string filename)
{
	string Country;
	string AlbumName;
	string SongTitle;
	string temp;
	ifstream Read;
//	Time m_Time;
//	int sec;
//	int min;
	Read.open(filename);
	m_Artist.SetName(AlbumName);
	m_Artist.SetCountryofOrigin(Country);
	getline(Read, Title);
	getline(Read, AlbumName);
	getline(Read, Country);
	for (int i = 0; i < 6; i++)
	{
		Time m_Time;
		int sec;
		int min;
		getline(Read, SongTitle);
		S[i].SetTitle(SongTitle);
		
		getline(Read, temp);

		min = stoi(temp);
		m_Time.SetMinutes(min);
		
		getline(Read, temp);

		sec = stoi(temp);
		m_Time.SetSeconds(sec);

		S[i].SetTime(m_Time);

	}
}

void Album::Write(string filename)
{
	cout << "Enter File Name" << endl;
	cin >> filename;
	ofstream Write;
	Write.open(filename);
	Write << GetTitle() << endl;
	Write << m_Artist.GetName() << endl;
	Write << m_Artist.GetCountryofOrigin();
	


	for (int i = 0; i < 6; i++)
	{
		Write << S[i].GetTitle() << endl;
		Write << S[i].GetTime().GetMinutes() << endl;
		Write << S[i].GetTime().GetSeconds() << endl;

	}
}

void Album::Display()
{
	cout << setw(12) << "Title:" << GetTitle() << endl;
	cout << setw(12) << "Artist:" << m_Artist.GetName() << endl;
	cout << setw(12) << "Title:" << m_Artist.GetCountryofOrigin() << endl;

}

Last edited on

a breakpoint poped up at min = stoi(temp); which is in the Read Method

Very good, so you know where the problem is.

You need to inspect with the debugger what value temp has.
If temp is not a valid int you need to find out how it got there.

So I didnt see anything that raised my suspicion but i saw that the int min wasnt never given a value. I’m still not sure if thats the problem but i set min and sec to 0 reran it and again it picked up a breaker but in a different location, now in the main.cpp cout << "Enter Choice: "; and I just dont see whats wrong with that code.

Edit: nevermind its still at the min = stoi(temp);

Last edited on

So in the debugger i noticed my temp has No value at all. So i made temp equal 0 temp = '0'; right before the loop and it seems to got rid of the error but still the program isnt working properly

Ok, the next step is to find out why it didn’t have a value.
Probably sth. wrong with your read function.
Without knowing the file format it’s impossible to tell.

Topic archived. No new replies allowed.

  • Remove From My Forums
  • Question

  • Hello im trying to use threads, but i cant stop the threads without getting the error: Abort() has been called.

    using namespace std;
    
    void print1()
    {
    	//while(true)
    	cout << "Function 1" << endl;
    }
    
    void print2()
    {
    	//while(true)
    	cout << "Function 2" << endl;
    }
    
    int main(int argc, char argv[])
    {
    	//Creates Threads
    	thread PrimaryThread(print1);
    	thread SecondaryThread(print2);
    
    	//Assigns the threas to pointers
    	thread* pPrimeThread = &PrimaryThread;
    	thread* pSecondaryThread = &PrimaryThread;
    
    	LPDWORD pExitCode = 0;
    	if(GetExitCodeThread(pPrimeThread,pExitCode) != 0)
    	{
    		ExitThread((DWORD)pExitCode);
    		cout << "Thread Closed" << endl;
    
    		if(CloseHandle(pPrimeThread))
            {
                cout << "Handle closed" << endl;
            }
    
    	}
    
    	system("pause");
        return 0;
    
    }

Answers

  • On 2/12/2013 3:36 AM, Farmek wrote:

    But it still gives me a «Abort() has been called» when i try to exit the application.

    You must call join() or detach() methods on thread object before that object is destroyed. If ~thread destructor is reached while the object is still attached to a thread of execution (in other words, while joinable() returns true), the destructor calls
    terminate().


    Igor Tandetnik

    • Marked as answer by

      Tuesday, February 12, 2013 3:12 PM

Comments

@DerKleinePunk

Log with LOG(DEBUG) << «Text» —> work
sdlLogger_->info(logText); —> don’t work
CLOG(INFO, «SDL») << logText; —> work

Visual Studio 2015 Update 3 Platform v140 Unicode

complier warnings:
easylogging++.cc(211): warning C4706: assignment within conditional expression
easylogging++.cc(1119): warning C4244: ‘/=’: conversion from ‘const double’ to ‘unsigned __int64’, possible loss of data

@abumusamq

Hi @DerKleinePunk,

can you please try following?

#undef ELPP_VARIADIC_TEMPLATES_SUPPORTED
#define ELPP_VARIADIC_TEMPLATES_SUPPORTED 1

and try to re-compile? If this works, let us know and I will add support for forcing VARIADIC_TEMPLATES as the header doesn’t have proper compiler flags to determine whether variadic templates are supported or not.

P.S Thanks for the warnings and I will note them but they are not the reasons for it’s not working

@DerKleinePunk

2 participants

@abumusamq

@DerKleinePunk

В приложении, которое я пишу, я использую исключения для большей части моей обработки ошибок. Я еще не определил свои собственные классы исключений, я просто сделал следующее:

namespace Mage {
typedef std::exception Exception;
}

Таким образом, мне не придется менять весь мой код, когда я позже определю свой собственный тип, который должен использовать тот же интерфейс.

Тем не менее, любое исключение вызывает сбой моего приложения. Принимая во внимание вышеприведенное определение, с чего бы это крушение?

void Mage::Root::initialize(Mage::String& p_log) {
// initialize GLFW and GLEW.
if (!glfwInit()) {
throw new Mage::Exception("failed to initialize OpenGL");
return;
} else m_GLFWInitialized = true;

Будь я удалить или оставить «новый», он все равно потерпит крах. Я что-то пропустил? Я посмотрел учебники, но они не делают меня мудрее.

Я также ловлю ошибку прямо здесь:

try {
MAGE_ROOT.initialize(Mage::String("Mage.log"));
} catch (Mage::Exception& e) {
std::cerr << e.what() << std::endl;
}

Авария, которую я получаю, это:

Debug Error!

Program: ...sual Studio 2010ProjectMage3DBinariesDebugTest.exe

R6010
- abort() has been called

(Press Retry to debug application)

1

Решение

Проблема в том, что вы не ловите свое исключение.

Я не знал, что ты должен поймать исключение (из комментариев)

Да, ты должен. Если вы не поймали выброшенное исключение, std::terminate() будет называться. Это предполагаемое поведение: существуют исключения, которые не позволяют программистам забывая об обработке ошибок.

Это сказал, я предлагаю:

  • метание по значению;
  • ловить по ссылке

Например:

void foo()
{
// ...
throw std::logic_error("Error!");
//    ^^^^^^^^^^^^^^^^^^^^^^^^^^^
//    Throw by value (std::logic_error derives from std::exception)
// ...
}

void bar()
{
try
{
// ...
foo();
// ...
}
catch (std::exception& e)
^^^^^^^^^^^^^^^
//     Catch by reference
{
std::cout << e.what(); // For instance...
}
}

ОБНОВИТЬ:

Что касается кода, который вы разместили, вы бросаете указатель и ловить ссылка. Обработчик не будет совпадать. И поскольку нет другого подходящего обработчика, std::terminate() будет называться.

Вместо этого вы должны выбросить исключение по значению:

throw Mage::Exception("failed to initialize OpenGL");

И если код, который вы разместили, действительно тот, который вы используете, вы увидите, что управление передается вашему обработчику.

11

Другие решения

Основываясь на сообщении об ошибке, вы используете Visual Studio (2010) для вашего проекта. Если вы не заключите свой бросок в блок try / catch, он будет «проплывать через крышу» и будет «обрабатываться» средой выполнения C ++, что означает вызов abort (). Вы, вероятно, хотите что-то подобное выше в стеке вызовов:

try
{
SomeFunctionThatUltimatelyThrows();
}
catch(Exception & e)
{
// .. handle error - log, resume, exit, whatever
}

Обратите внимание также на совет Скотта Мейерса всегда отлавливать исключения по ссылке. «Исключение»: если вы используете исключения MFC CExceptions, вы хотите перехватить указатель и вызвать метод Delete для самоуничтожения исключений на основе кучи.

Основываясь на ваших изменениях, вы можете иметь несоответствие между броском «по указателю» и отловом «по ссылке». Если вы решили это и по-прежнему не выполняете свой блок catch, вы можете попробовать отладить вызов abort () с помощью CRT SetAbortHandler, чтобы установить собственную функцию прерывания. Это может просто включить в существующую, но даст возможность установить точку останова и проверить стек вызовов, чтобы увидеть, что происходит не так.

2

C ++ try-catch-throw логика для чайников. Обратите внимание, что это НЕ охватывает RAII / размещение / уничтожение на основе стека.

  • Когда вы выбрасываете исключение, исключение называется «распространяющимся». Он распространяется вверх по стеку вызовов до тех пор, пока не найдет первый обработчик, который сможет его обработать (чтобы он был перехвачен), или пока он не достигнет корня стека вызовов.
    • Если он перехвачен, выполнение продолжается с того момента, когда перехвачено исключение. Исключение уничтожается в конце блока catch.
    • Если он находит корень, он вызывает std :: unhandled_exception, который обычно вызывает std :: terminate, который обычно вызывает abort (). Короче говоря, все выпало как можно скорее.
  • Если вы генерируете исключение во время распространения исключения, у вас будет по два одновременно. Java и C # имеют хитроумные способы справиться с этим, но это никогда не должно происходить в первую очередь — нет обработчика исключений, который логически собирается обрабатывать комбинации исключений. Не выбрасывайте исключения, пока одно из них распространяется. Это правило не слишком сложно соблюдать, даже если вы не используете std :: uncaught_exception (), чего не следует делать.
  • При разматывании стека / распространении исключения все объекты, найденные в стеке, уничтожаются. Эти деструкторы никогда не должны выдавать исключение — в конце концов, когда уничтожение объекта «не удается», что еще вы будете делать после того, как деструктор его исправит?
  • Всегда бросать по значению, ловить по ссылке. Если вы бросите & поймать по указателю, вы, скорее всего, что-то утечет, что невозможно по ссылке. Если вы поймете по значению, вы отрежете свои производные типы исключений. Поймать по ссылке.
  • В корне вашего программного обеспечения, включить всеобъемлющее — catch(...), Это не позволяет вам узнать, что именно вы поймали, но, по крайней мере, вы можете безопасно потерпеть крах. Делайте это также, когда вызываемый код может выбросить «что-то», чего вы не знаете.

1

Понравилась статья? Поделить с друзьями:
  • Ошибка a811 bmw x5 e70
  • Ошибка a72f bmw x5 e70
  • Ошибка a670 bmw x5 e70
  • Ошибка a5 1 toyota погрузчик
  • Ошибка a4 bosch gaz 7000