c++ - 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;
}
解决方案
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]
非法,导致失败
推荐阅读
- apache-spark - Spark分区发现的自定义配置
- c++ - 我试图通过我的代码找到任何数字的素数。但是对于大量数字,我的代码不会终止。为什么?
- macros - 用于为页面上的所有形状提供公共边框的宏
- azure - 从 SAS 链接下载文件而不是文件的完整路径时,Azure.Storage.Blobs 获取文件名
- python - 如何在类函数中使用递归
- laravel - Laravel Queue 队列:在共享主机后台运行的工作(CPanel)
- go - 检测符号链接
- python - 以错误的间隔或格式为输入引发异常
- python - Countplot 函数不适用于分箱数据
- java - Spring AMQP - 应用程序启动时未创建 RabbitMQ 连接