【发布时间】:2018-04-02 13:36:47
【问题描述】:
之前,我一直在 CodeBloks 中使用 C++ 进行一些编程,从一段时间以来,我开始在 MS Studio 中进行编程。目前我正在编写书中的一个小游戏:编程:使用 C++ 的原则和实践。第 5 章的练习 12。 我一直在互联网上四处寻找,以修复无论我尝试什么都会不断发生的范围内存错误(请参阅打印屏幕链接)。 关于程序的描述在代码本身中。 我还确实将向量设置为硬编码(如果我说得对的话)大小,以使程序不再抱怨它们的内存范围错误。
注意:是的,这也是一个学校练习/练习。但是我宁愿问我做错了什么,然后从互联网上复制粘贴代码..
请查看我的代码并查看,否则我在向量方面犯了一些错误,因为这可能是我的错误的来源。
更新:作为本主题的答案。 Link to update
错误:
Unhandled exception at 0x7529CBC2 in Tweede project.exe: Microsoft C++ exception: Range_error at memory location 0x006FF510.
程序:
#include "std_lib_facilities.h"
int main(){
bool while_bit = false;
vector<int>bulls_cows(4);
vector<int>inputs_arr(4);
//Generate 4 random numbers.
for (int a = 0; a < 4; ++a){
bulls_cows[a] = a + 1;//randint(a) % 9 + 0; //random number between 0 and 9.
}
//bulls_cows[1] = randint(10);
cout << "For this game, called Bulls and Cows, you have to guess the four right numbers between 0 and 9.\n";
cout << "When one or more digets are right and in the right position the program will say the number of Bulls.\n";
cout << "When one or more digets are right but not in the right position the program will say the number of Cows.\n";
cout << "Please enter 4 number by filling in ONE positive diget and press enter. Do this four times and wait for the result.\n";
for (int z = 0; z < 4; ++z) {
cout << bulls_cows[z] << "\n";
}
while (while_bit == false) {
int input = 0; //Reset of input, cows and bulls every round.
int cows = 0;
int bulls = 0;
cin >> input;
//Test for legit input. If legit then it writes it to the array called "input_arr"
if (input < 0 || input > 9) {
cout << "Number must be between 0 and 9.\n";
}
else {
inputs_arr.push_back(input);
}
//Check or 4 numbers have been given.
if (sizeof(inputs_arr) < 4) {
//Check for equal numbers on same spot.
for (int b = 0; b < 4; ++b) {
if (inputs_arr[b] == bulls_cows[b]) {
bulls + 1;
}
}
//Check for a number in all spots.
for (int c = 0; c < 4; ++c) {
if (inputs_arr[c] == bulls_cows[0] || bulls_cows[1] || bulls_cows[2] || bulls_cows[3]) {
cows +1;
}
}
}
if (bulls < 4) {
cout << "You did not guess the right combination.\n";
cout << "Number of bulls: " << bulls << "\n";
cout << "Number of cows: " << cows << "\n";
inputs_arr[0, 0, 0, 0]; //Empty array.
}
if (bulls == 4) {
cout << "You guessed the right combination!\n";
while_bit = true;
}
}
keep_window_open(); //To keep terminal open since MS Studio doesn't itself.
return 0;
}
【问题讨论】:
-
请不要链接文字图片。只需输入文本本身,可能标记为引号或代码。
-
std_lib_facilities.h那是什么? -
谷歌 sizeof 运算符的作用
-
std_lib_facilities.h 是书中的一个库。它有最基本的库,如
、 和如果我是正确的 。它还具有一些额外的功能,例如保持提示/终端打开以便您查看结果的功能。 -
会做@Deduplicator。将编辑帖子。
标签: c++ c++11 visual-c++