首页 > 解决方案 > basic_string::_M_construct null 无效问题

问题描述

我在制作二十一点游戏时遇到了一个问题,不太确定如何自己解决。抛出 'std::logic_error' what(): basic_string::_M_construct null not valid 的实例后,错误读取终止调用。问题似乎来自对 calculateScores() 方法的最终调用,但不确定为什么会出现问题。

#include <iostream>

using std::string;
using std::cout;
using std::cin;
using std::endl;

bool someoneWon = false;
const char* cards[] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};
string names[] = {"Dealer", "Ethan", "Brian", "Taha"};
int randNum1, randNum2;
int dealerScore, ethanScore, brianScore, tahaScore, playerScore = 0;

void calculateScores(int num1, int num2, string iName) {
    //Add scores
    if (iName == names[0]) dealerScore += num1 += num2;
    else if (iName == names[1]) ethanScore += num1 += num2;
    else if (iName == names[2]) brianScore += num1 += num2;
    else if (iName == names[3]) tahaScore += num1 += num2;
    else if (iName == names[4]) playerScore += num1 += num2;
    //Checks for winner
    if (dealerScore > 20) {
        cout << "Dealer has won";
        someoneWon = true;
    } else if (ethanScore > 20) {
        cout << "Ethan has won";
        someoneWon = true;
    } else if (brianScore > 20) {
        cout << "Brian has won";
        someoneWon = true;
    } else if (tahaScore > 20) {
        cout << "Taha has won";
        someoneWon = true;
    } else if (playerScore > 20) {
        cout << "You won";
        someoneWon = true;
    }
}

void startGame() {
    for (int i=0; i<5; i++) {
        randNum1 = rand() % 13;
        randNum2 = rand() % 13;
        //dealer
        if (i == 0) {
            cout << "Dealer has " << cards[randNum1] << " and another hidden card." << endl;
            calculateScores(randNum1, randNum2, names[i]);
        //AI players
        } else if (i < 4) {
            cout << names[i] << " has a " << cards[randNum1] << " and a " << cards[randNum2] << endl;
            calculateScores(randNum1, randNum2, names[i]);
        //Actual player
        } else {
            cout << "You have a " << cards[randNum1] << " and a " << cards[randNum2] << endl;
            calculateScores(randNum1, randNum2, names[i]);
            char userOption; cout << "Would you like to hit or stand? (h/s): "; cin >> userOption;
        }
    }
}

int main() {
    system("cls");
    startGame();
    return 0;
}

标签: c++

解决方案


TL博士

string names[] = {"Dealer", "Ethan", "Brian", "Taha" }; // Problem

string names[] = {"Dealer", "Ethan", "Brian", "Taha", "foo" }; // Fix

长答案

在 for 循环中,for (int i=0; i<5; i++)如果i == 4它进入else

} else {
            cout << "You have a " << cards[randNum1] << " and a " << cards[randNum2] << endl;
            calculateScores(randNum1, randNum2, names[i]);
            char userOption; cout << "Would you like to hit or stand? (h/s): "; cin >> userOption;
        }

在这个 else 下面的语句试图访问names[i]这里i是 4 calculateScores(randNum1, randNum2, names[i]);names定义为

string names[] = {"Dealer", "Ethan", "Brian", "Taha"};

使访问names[4]非法,导致失败


推荐阅读