我正在尝试为我的编程类编写一个程序,该程序成功运行一个数字1-6的主脑游戏作为输入而不是颜色。当我尝试按原样测试程序时,我收到消息
“0 [main] Lab16 9828 cygwin_exception :: open_stackdumpfile:将堆栈跟踪转储到Lab16.exe.stackdump”
评论代码的各个部分似乎没什么帮助。我对所有这些都很苛刻,所以我们对任何经验教训表示赞赏。
非常感谢任何帮助/建议!感谢您阅读我的问题!
/** INCLUDE FILES ***************************************************/
#include <iostream> // input output commands: cout & cin
#include <iomanip>
#include <vector>
#include <cmath>
#include <cstdlib>
using namespace std;
/** FUNCTION PROTOTYPES**********************************************/
void GetPatterns(vector <int> &x); // Gets user pattern
void CreateSolution(vector <int> &y); // Creates the right pattern before user input
bool SolutionCalc(vector <int> x, vector <int> y); // Detects how many guesses are correct and or in the right place, returns bool value to main()
/** MAIN FUNCTION ***************************************************/
int main()
{
/** VARIABLE DECLARATION ****************************************/
bool solution;
vector <int> UserPattern;
vector <int> RealPattern;
srand(time(0));
/** FUNCTION CALLS***********************************************/
CreateSolution(RealPattern);
do
{
GetPatterns(UserPattern);
solution = SolutionCalc(UserPattern,RealPattern);
}while(solution == false);
cout << "Correct!" << endl;
cout << "You are a Mastermind!" << endl;
return 0;
}
/** FUNCTIONS *******************************************************/
void GetPatterns(vector <int> &x)
{
cout << "Welcome to Mastermind." << endl;
cout << endl;
cout << "Please enter your four numerical guesses(space separated, numbers 1-6): ";
for (int i = 0; i < 4; i++) // 4 size vector array for user input
{
cin >> x[i];
}
cout << endl;
}
void CreateSolution(vector <int> &y)
{
for(int e = 0; e < 4; e++) // 4 size vector array for solution
{
y[e] = rand()%6+1;
}
cout << endl;
}
bool SolutionCalc(vector <int> x, vector <int> y) // Z is the bool to check if the solution is solved or not
{
int RightNum = 0, RightPlace = 0;
bool IsSolution;
for (int i = 0; i < 4; i++)
{
if (x[i] == y[i])
{
RightPlace++;
}
if ((x[i] != y[i]))
{
if(x[i] == y[0] || x[i] == y[1] || x[i] == y[2] || x[i] == y[3])
{
RightNum++;
}
}
}
if (RightNum < 4)
{
cout << "You have " << RightNum << " correct number(s) and " << RightPlace << " correct locations(s)." << endl;
IsSolution = false;
}
else if (RightNum == 4)
{
IsSolution = true;
}
return IsSolution;
}
答案 0 :(得分:1)
当您默认初始化它们时,您假设所有向量都有四个元素。向量的默认初始化生成具有零元素的向量,因此当您访问向量的第一个到第四个元素时,超出向量的边界。
这是我所谈论的一个简短例子:
std::vector<int> myvector;
myvector[1] = 3; // oh no!
您有三种方法可以解决此问题。您可以预定义矢量的大小:
std::vector<int> myvector(4);
myvector[1] = 3; // ok
或者您可以在填充它时将其更改为适当的尺寸:
std::vector<int> myvector; // elsewhere
myvector.resize(4);
myvector[1] = 3; // okay
或者您可以在填充数组时动态调整数组的大小:
std::vector<int> myvector; // elsewhere
for(size_t index = 0; index < 4; ++index){
myvector.push_back(someNumber); // also okay
}
使用所有语法,一旦您填充了向量,就可以使用operator[]
以您期望的方式访问元素。只要确保不要超过矢量的界限!您可以通过调用size
来检查向量的大小,如下所示:myvector.size();