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
-
Marked as answer by
- 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
|
|
Album.cpp
|
|
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++. Нужно немного помощи. Сам код:
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, Инициализируй массивы нулем в 8-ой строчке так: Добавлено через 2 минуты 1 |
«C with Classes» 1610 / 1383 / 518 Регистрация: 16.08.2014 Сообщений: 5,755 Записей в блоге: 1 |
|
25.02.2019, 15:34 |
4 |
ForeverFast,
И проверь логику. у тебя в коде черт ногу сломит, «Бери ношу по себе, чтоб не падать при ходьбе.». Ты когда пишешь блок кода, и он у тебя не работает должным образом, зачем ты на следующий блок переходишь? 1 |
ForeverFast 3 / 3 / 1 Регистрация: 13.12.2018 Сообщений: 214 |
||||
27.02.2019, 13:54 [ТС] |
5 |
|||
Спасибо большое. Учёл ваши замечания и переписал код, максимально его упростив.
Если есть ещё какие либо замечания, буду рад услышать и запомнить их на будущее. 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
|
|
Album.cpp
|
|
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
-
Marked as answer by
Comments
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
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
2 participants
В приложении, которое я пишу, я использую исключения для большей части моей обработки ошибок. Я еще не определил свои собственные классы исключений, я просто сделал следующее:
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