Unhandled exception at 0x00FB59E6 [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I've been looking over my code for awhile now, and I can't figure out why this error keeps coming up. It's probably something really simple, but I just can't figure it out...
"Unhandled exception at 0x00FB59E6 in program.exe: 0xC0000005: Access violation writing location 0x00000009."
It happens on the third time of repeating the program
main.cpp
#include <iostream>
#include <string>
#include "functions.h"
using namespace std;
int main(){
RandomArray();
MinMaxArray();
SortedArrays();
cout << "\n\nWould you like to re-run? (Y/N): ";
cin >> y;
if (y == "Y" || y == "y"){
system("CLS");
main();
}else{
system("PAUSE");
}
return 0;
}
functions.h
#include <iostream>
#include <time.h>
using namespace std;
int array[50], used[50], sortedArray[50];
int buildSort = 1, genNum, mx = 0, mn = 100;
bool x;
string y;
int RandomArray(){
srand(time(0));
for(int a = 0; a < 50; a++){ //array generator
do{
genNum = (1+rand()%100); //generate a # between 1-100
x = false;
for(int b = 0; b < 50; b++){
if(genNum == used[b]){ //if the number is already used...
x = true;
}
}
}while(x == true);
used[a] = genNum;
array[a] = genNum;
}
cout << "Random array: " << endl;
for(int c = 0; c < 50; c++){
cout << array[c] << " "; //display the random array
}
cout << endl << endl;
return 0;
}
int MinMaxArray(){
for(int d = 0; d < 50; d++){ //for each number in the array
if(array[d] > mx){ //check to see if each number is greater than mx
mx = array[d]; //the max equals that number it picked out
}
if(array[d] < mn){ //check to see if theres a number is less than mn
mn = array[d]; //the minimum equals that number it picked out
}
}
cout << "Maximum: " << mx << endl; //display the max
cout << "Minimum: " << mn << endl << endl; //display the min
return 0;
}
int SortedArrays(){
sortedArray[0] = mn;
for(int e = mn + 1; e <= mx; e++){ //goes through 1-100 and adds each number to another array in order
for(int f = 0; f < 50; f++){
if(array[f] == e){
sortedArray[buildSort] = array[f];
buildSort++;
}
}
}
cout << "Sorted array: " << endl;
for(int g = 0; g < 50; g++){
cout << sortedArray[g] << " "; //display sorted from lowest to highest
}
cout << endl << endl;
cout << "Reverse sorted: " << endl;
for(int h = 49; h >= 0; h--){
cout << sortedArray[h] << " "; //display sorted from highest to lowest
}
return 0;
}

You are using some variables that you are initializing just the 1st time: buildSort, mx and mn;
Add at the beginning of your main something like
int main()
{
buildSort = 1;
mx = 0;
mn = 100;
RandomArray();
MinMaxArray();
SortedArrays();
}
And try again.
Your buildSort makes you run out of the array.
Just a suggestion: try to write your code better! Is almost unreadable!!!

Don't use global variable (at least not like this!)
There is not need to use system function for basic features like CLS and PAUSE, you may use clrscr() or getch() (or appropriate functions)
Don't recurse main - it it not meant for this purpose. Though no compiler will complain, it is bad approach.

Related

Run-Time Check Failure #2 - Stack around the variable 'numberchoices' was corrupted

I am having this terminal error every time I finish the debug program.
What I am doing:
[this program is a simple Lottery Numbers Comparison between user input numbers with the non-repeated random lottery numbers. e.g. using what if it got 4 right of 6]
but it turns out that the program is not working or at least, be stable.
Here's my code:
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <time.h>
#include <ctime>
#include <algorithm>
using namespace std;
int main()
{
cout << "[La Loteria Electronica]\n";
cout << "Escoge 6 n" << char(163) << "meros del (1 al 49): \n";
int numberchoices[] = { 0 };
for (int w = 1; w < 7; w++)
{
cout << "N" << char(163) << "mero #" << w << ": ";
cin >> numberchoices[w];
} // user numbers
//lottery numbers
int i, j, k, nums[51];
srand((int)time(0));
for (i = 1; i < 50; i++) nums[i] = i;
for (i = 1; i < 50; i++)
{
j = (rand() % 49) + 1;
k = nums[i]; nums[i] = nums[j]; nums[j] = k;
}
cout << "The lottery numbers are: ";
for (i = 1; i < 7; i++) cout << nums[i] << " ";
if (numberchoices[i] = nums[i])
{
cout << "gud\n";
}
if (numberchoices == nums)
{
cout << "gud 2";
}
/**/
cout << "\n\n";
system("pause");
Please ?
int numberchoices[] = { 0 };
for (int w = 1; w < 7; w++)
{
cout << "N" << char(163) << "mero #" << w << ": ";
cin >> numberchoices[w];
} // user numbers
You're declaring an array of size 1 and then you use it up to position 6 ?
I am having this terminal error every time I finish the debug program.
I'm surprised that you're not having a terminal error every time you start debug.
The access of numberchoises at positions from 1 to 6 are UB (Undefined Behavior). That is: all can happens.
Solution: try with
int numberchoices[7] = { }; // initialize all elements to zero!
Another point
if (numberchoices == nums)
not sure that you get what do you expect.
Do you want compare the integer pointer corresponding to numberchoices (a int[1], suggested int[7]) with the one corresponding to nums (a int[51]) ?

How do you get cin to only accept numbers from user input? [duplicate]

This question already has answers here:
How to make cin take only numbers
(2 answers)
Closed 6 years ago.
So the requirements for this program is to be able to increment arrays of the same size (size from 5 to 15 indexes) and increment each element in the array by one using for and while loops. The last task is to take values from the first array and put them in reverse order and assign them to the second array.
So everything works as normal, and the program rejects invalid inputs and does not go into an infinite loop. However, the program accepts some inputs that are not wanted.
For example, I would input something like '12 a' or '7 asdfkla;j lasnfg jasklgn asfg' and it would go through. It is interesting too because the code registers only 12 or 7 and completely ignores the rest. I think it is because once it hits a non-integer character, it would stop ignore the rest.
Why is it ignoring the rest of the input? And is there a way to catch this error from going through?
Also, if you see anything that catches your eye, feel free to critique c: I am always looking to improving.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
srand(time(NULL));
int x;
int j = 0;
bool not_valid = true;
system("color f");
cout << "Program will ask for an input for the size of an array.\n"
<< "With the array size defined, program will generate semi-\n"
<< "true random integers from 0 to 8. First array will then\n"
<< "be assigned to the second in reverse (descending) order.\n\n";
do {
cout << "Enter array size (0 - 15): ";
cin >> x;
if (x >= 5 && x <= 15) {
not_valid = false;
cout << "\nArray size: " << x << endl;
}
else {
cout << "Invalid input.\n\n";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
} while (not_valid);
int *arr0;
int *arr1;
arr0 = new int[x];
arr1 = new int[x];
for (int i = 0; i < x; i++) {
arr0[i] = rand() % 9;
}
for (int i = 0; i < x; i++) {
arr1[i] = rand() % 9;
}
cout << "\nARRAY 0 (unmodified, for):\n";
for (int i = 0; i < x; i++) {
cout << arr0[i] << "\t";
}
cout << "\n\nARRAY 0 (modified, for):\n";
for (int i = 0; i < x; i++) {
arr0[i]++;
cout << arr0[i] << "\t";
}
cout << "\n\nARRAY 1 (unmodified, while):\n";
for (int i = 0; i < x; i++) {
cout << arr1[i] << "\t";
}
cout << "\n\nARRAY 1 (modified, while):\n";
while (j < x) {
arr1[j]++;
cout << arr1[j] << "\t";
j++;
}
int second = x - 1;
for (int i = 0; i < x; i++) {
arr1[second] = arr0[i];
second--;
}
j = 0;
cout << "\n\nARRAY 1 (array 0, descending):\n";
while (j < x) {
cout << arr1[j] << "\t";
j++;
}
cout << endl << endl;
system("pause");
return 0;
}
Take input in string and then check if it's a number or not.
Example:
#include<iostream>
#include<sstream>
#include <string>
using namespace std;
int main()
{
string line;
int n;
bool flag=true;
do
{
cout << "Input: ";
getline(cin, line);
stringstream ss(line);
if (ss >> n)
{
if (ss.eof())
{
flag = false;
}
else
{
cout << "Invalid Input." << endl;
}
}
}while (flag);
cout << "Yo did it !";
}

C++ Receiving error that the function was not declared in this scope [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
This is the porgram I am writing for my university's Assignment. I have written all the codes that takes 10 integers from user, and asks user to press 1 to show odd integers in ascending order from the list or 2 to show the even integers in ascending order from the list.
Well, I have declared and defined the Bubble Sorting function before the main() function in program, and used the function later in main() to sort the even and odd numbers in ascending order. But, I am still getting the error that the function was not declared in this scope even when I have declared it at the top. I tried all possible things I could do. Kindly help me what should I do? Below is my code
#include <iostream>
#include <conio.h>
using namespace std;
void BuubleSort_Function(int [], int);
void BuubleSort_Function(int arr[], int arrSize)
{
int extraMem;
for(int i = 0; i < arrSize; i++)
{
for(int arrIndex = 0; arrIndex < arrSize - 1; arrIndex++)
{
if(arr[arrIndex] > arr[arrIndex+1])
{
extraMem = arr[arrIndex];
arr[arrIndex] = arr[arrIndex+1];
arr[arrIndex+1] = extraMem;
}
}
}
}
main()
{
int num[10], i, even[10], odd[10], inputOpt, totalEvens = 0, totalOdds = 0;
system("cls");
cout << "Please enter 10 integers: " << endl;
for(i = 0; i < 10; i++)
{
cin >> num[i];
}
cout << endl << endl << endl << "1. Show odd numbers in ascending order and their total numbers" << endl;
cout << "2. Show even numbers in ascending order and their total numbers" << endl;
do
{
cout << endl << "Enter 1 for the first option or 2 for the second option: ";
cin >> inputOpt;
if(inputOpt != 1 && inputOpt != 2)
{
cout << "Wrong Input! Please enter the correct input value";
}
}
while(inputOpt != 1 && inputOpt != 2);
if(inputOpt == 1)
{
for(i = 0; i < 10; i++)
{
if(num[i] % 2 == 1)
{
odd[totalOdds] = num[i];
totalOdds++;
}
}
BubbleSort_Function(odd,totalOdds);
cout << endl << "The total numbers of Odds Integers are " << totalOdds;
cout << endl << "The Integers arranged in Ascending Order:" << endl;
for(i = 0; i < totalOdds; i++)
{
cout << odd[i] << "\t";
}
}
if(inputOpt == 2)
{
for(i = 0; i < 10; i++)
{
if(num[i] % 2 == 0)
{
even[totalEvens] = num[i];
totalEvens++;
}
}
BubbleSort_Function(even,totalEvens);
cout << endl << "The total numbers of Odds Integers are " << totalEvens;
cout << endl << "The Integers arranged in Ascending Order:" << endl;
for(i = 0; i < totalEvens; i++)
{
cout << even[i] << "\t";
}
}
}
A simple typo: the function is declared and implemented as BuubleSort_Function.
You attempt to call it using BubbleSort_Function.
The compiler error messages are very helpful. Do learn to interpret them.
(Finally, standard C++ requires you to mark main() as returning an int - a C++ compiler will insert an implicit return 0 into main if it's missing. Some compilers - especially ones for embedded systems - drop this requirement but that is a deviation from the standard.).
Defination - BuubleSort_Function
Caller - BubbleSort_Function
Compare the 5th line and the 7th line with the 64th line,and you will find what the problem is.Just a simple typo.

Array printing out multiple characters in basic dungeon crawler [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
My name is Eric, and I ran into a problem while programming a basic "dungeon crawler" using c++.
The problem is that when the player moves certain spaces to the left or right, there is another player character generated so that there is two on the screen instead of one.
Here is my code:
#include <iostream>
#include <time.h>
#include <stdlib.h>
#include <string>
using namespace std;
const int columns = 7, rows = 10;
string gridArray[rows][columns];
bool xIsGenerated = false;
bool gISGenerated = false;
int playerX = 0, playerY = 0;
void displayGrid(int rows, int columns){
for(int i = 0; i < columns; i++){
for(int x = 0; x < rows; x++){
cout << gridArray[i][x];
}
cout << endl;
}
cout << gISGenerated << endl;
return;
}
void generatePieces(int rows, int columns){
int tcount = 0;
for(int i = 0; i < rows; i++){
for(int x = 0; x < columns; x++){
srand(time(NULL) + x + i);
int r = rand() % 5;
if(r == 1 && tcount < 4){
gridArray[i][x] = "T ";
tcount++;
}else if(r == 2 && !xIsGenerated){
gridArray[i][x] = "X ";
xIsGenerated = true;
}
}
}
if(!xIsGenerated){
srand(time(NULL)*3);
int r = rand() % rows+1;
int c = rand() % columns+1;
gridArray[r][c] = "X ";
xIsGenerated = true;
}
return;
}
void generatePlayer(int rows, int columns){
if(!gISGenerated){
srand(time(NULL)*3);
int r = rand() % rows+1;
int c = rand() % columns+1;
gridArray[r][c] = "G ";
playerX = r;
playerY = c;
gISGenerated = true;
}
}
void initGrid(int rows, int columns){
for(int i = 0; i < columns; i++){
for(int x = 0; x < rows; x++){
gridArray[i][x] = ". ";
}
}
generatePieces(rows, columns);
generatePlayer(rows, columns);
return;
}
//i is the rows
//x is the columns
void movePlayer(){
char input = 'x';
cin >> input;
if(input == 'w' && playerX != 0){
gridArray[playerX][playerY] = ". ";
gridArray[playerX-1][playerY] = "G ";
playerX--;
}
if(input == 's' && playerX != 6){
gridArray[playerX][playerY] = ". ";
gridArray[playerX+1][playerY] = "G ";
playerX++;
}
if(input == 'a' && playerY != 0){
gridArray[playerX][playerY] = ". ";
gridArray[playerX][playerY-1] = "G ";
playerY--;
}
if(input == 'd' && playerY != 9){
gridArray[playerX][playerY] = ". ";
gridArray[playerX][playerY+1] = "G ";
playerY++;
}
system("CLS");
displayGrid(rows, columns);
cout << playerX << ": " << playerY << endl;
}
void firstTime(){
displayGrid(rows, columns);
cout << playerX << ": " << playerY << endl;
return;
}
int main()
{
initGrid(rows,columns);
firstTime();
while(true){
movePlayer();
}
return 0;
}
Quick explanation of code:
A multidimensional array will serve as the graphic for displaying what is going on. This array starting with the function "initGrid" will print out ". " strings in the array and on the screen
The Generate Pieces function takes that array filled with ". " strings, and using a random number generator, it places "T " strings and 1 "X " string. This "X " will be the goal while the T's will be traps that kill the player.
Generate Player does the same thing, but instead places only 1 "G " string. This is the player.
After initGrid is called, then inside of the main function is the "firstTime" function, nothing complex, just displays data to the screen.
Then lastly, I have a while loop that calls the function "movePlayer", using the same array, based on what the user inputs, it will move the "G " string accordingly and replace the last location of the g string with an empty ". " string.
I have tried to return the location of the second G string and once I did that I tried to replace it with a ". " string, but it failed as the code didn't remove the second one, and once the second one was out of the array (the second g character moves corresponding to the first g character) the first G character got removed.
I am drawing a blank here as to what I should do next, it seemed to be a simple problem at first, but it is giving me a run for it's money.
Thanks for reading, and I hope to get an answer soon to my problem.
I ran your code with asan and ubsan which told me you have an out of bounds access in line 23 cout << gridArray[i][x]; where you access gridArray[8] which doesn't exist.
Looks like you mixed up rows and columns. I recommend you use sanitizers too.

Histogram program aid

I am a bit stuck with my program, The program is to Read in a set of results and then construct a histogram that indicates how many marks are in each decade i.e how many between 10-20 etc.
I have 2 problems
How can I edit my code to only allow the readExamResults to store ones in the range of 0 -100
How can I get the PrintHisto to print the * at a certain setw() dependant on which decade each of the results where in. e.g. If I entered 3,4,5,11,23 It should show 3 * in the <10 decade, 1 in the 10-20 decade and 1 in the 20-30 decade.
any help will be much appreciated.
code:
using namespace std;
void readExamMarks(int examMarks[], int sizeOfArray){
cout << "Please enter a set of exam marks to see a histogram for:" << endl;
int x = 0;
for( int idx = 0; idx < sizeOfArray; idx++){
cin >> x;
examMarks[idx] = x;
}
}
void printExamMarks(int examMarks[], int sizeOfArray){
for(int x = 0; x < sizeOfArray; x++){
cout << setw(5) << examMarks[x];
}
cout << endl;
}
void printHisto(int examMarks[], int sizeOfArray){
system("cls");
for( int x = 0; x < 6; x++){
cout << setw(5) << "*" << endl;
}
}
int main()
{
int examMarks[5];
readExamMarks(examMarks, 5);
printHisto(examMarks, 5);
printExamMarks(examMarks,5);
system("PAUSE");
}
How can I edit my code to only allow the readExamResults to store ones
in the range of 0 -100
I guess you meant readExamMarks rather than readExamResults. If so, you would just need to add an if statement to check that the input value is actuall in the range [0..100]. I have also changed your loop statement for to a while because you just want to increase idx when a valid number is entered.
void readExamMarks(int examMarks[], int sizeOfArray)
{
cout << "Please enter a set of exam marks to see a histogram for:" << endl;
int x = 0;
int idx = 0;
while(idx < sizeOfarray)
cin >> x;
if((x >=0) && (x <= 100)){
examMarks[idx] = x;
idx++;
}
else
cout << "ERROR: Value must be in range [0...100], please enter a valid value\n";
}
}
Basically you create a new array with an entry for each decade. Then iterate over the exam grades and increase the according decade in the histogram:
vector<int> calculateHistogram(vector<int> grades)
{
vector<int> histogram(10, 0);
for (int i=0; i<grades.size(); i++) {
int decade = grades[i]/10;
histogram[decade] += 1;
}
return histogram;
}