每次我启动此应用程序时,它都会进入工作正常的菜单,但是在我按下start()之后,它只会中止运行,并且我有理论认为这是stoi,但我不确定。如您所见,我正在制作二十一点游戏,它使用数组然后将rand()随机从数组中移出,但随后必须将数组中的字符串转换为整数。但是然后您必须担心数组中的国王或0,所以我不得不考虑这一点。

// Blackjack.cpp
#include "stdafx.h"
#include <iostream>
#include <string>
#include <cstdlib>
#include <Windows.h>
#include <ctime>
#include <string>

using namespace std;

int start(); // forward decleration

int main() {
    int menu = 0;
    SetConsoleTitle(TEXT("BlackJack By Paul V 1.0"));
    cout << "Welcome to BlackJack!" << endl;
    cout << "1. Start the game!!" << endl;
    cout << "2. Exit" << endl;
    cout << "ENTER HERE:" << flush;
    cin >> menu;
    if (menu == 1) {
        start();
    }
    if (menu == 0) {
        cout << "Program Ending....." << endl;
    }
    return 0;
}
int start() {
    SetConsoleTitle(TEXT("LOADING....."));
    srand((unsigned)time(NULL));
    int menu = 0;
    int yo1 = rand() % 13;
    int yo2 = rand() % 13;
    int yo3 = rand() % 13;
    int yo4 = rand() % 13;
    int yo5 = rand() % 13;
    int yo6 = rand() % 4;
    int yo7 = rand() % 4;
    int yo8 = rand() % 4;
    int yo9 = rand() % 4;
    int yo = rand() % 4;
    int card1 = 0;
    int card2 = 0;
    int card3 = 0;
    int card4 = 0;
    int card5 = 0;
    string card_names[13] = { "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King" };
    string card_types[4] = { "Diamonds", "Spades", "Clubs", "Hearts" };
    string goody = card_names[yo1];
    string goddy2 = card_names[yo2];
    string goddy3 = card_names[yo3];
    string goddy4 = card_names[yo4];
    string goddy5 = card_names[yo5];
    if (yo1 == 10 || yo1 == 11 || yo1 == 12) {
        const int card1 = 10;
    }
    if (yo2 == 10 || yo2 == 11 || yo2 == 12) {
        const int card2 = 10;
    }
    if (yo3 == 10 || yo3 == 11 || yo3 == 12) {
        const int card3 = 10;
    }
    if (yo4 == 10 || yo4 == 11 || yo4 == 12) {
        const int card4 = 10;
    }
    if (yo5 == 10 || yo5 == 11 || yo5 == 12) {
        const int card5 = 10;
    }
    if (yo1 == 0) {
        const int card1 = 1;
    }
    if (yo2 == 0) {
        const int card2 = 1;
    }
    if (yo3 == 0) {
        const int card3 = 1;
    }
    if (yo4 == 0) {
        const int card4 = 1;
    }
    if (yo5 == 0) {
        const int card5 = 1;
    }
    else {
        int card1 = stoi(card_names[yo1]);
        int card2 = stoi(card_names[yo2]);
        int card3 = stoi(card_names[yo3]);
        int card4 = stoi(card_names[yo4]);
        int card5 = stoi(card_names[yo5]);
    }
    SetConsoleTitle(TEXT("BlackJack By Paul V 1.0"));
    cout << "Your starting card is a " << goody << " of " << card_types[yo6] << endl;
    return 0;
}

最佳答案

问题出在您的stoi()上。这是因为yo'n'的值会一直延伸到代码的最后一个“else”部分,即使它们超出了1到9的范围。

您需要先对所有yo'n'变量进行范围检查,然后再将它们作为card_names [yo'n']传递给stoi。

正如smead所说,请编写更简洁的代码。太多的“如果”使它几乎不可读和不可调试。

10-07 16:50