Strange characters appearing in 2D Char Array - c++

I'm coding a game that utilizes a 'grid', which I have created using a 2 dimensional array of structs, which contain a char value and a boolean value. In my program's .h file, I declare the struct and create the grid.
struct Tile
{
char letter;
bool active;
};
Tile grid [6][5];
In my .cpp file, I initialize the grid so that all values are blank.
for (int i = 0; i < 7; ++i)
{
for (int j = 0; j < 6; ++j)
{
grid[i][j].active == false;
//grid[i][j].letter = '.';
//it always crashes when i try doing the above line
}
}
The function that prints the grid, printGrid, is below
for (int i = 0; i < 7; ++i)
{
for (int j = 0; j < 6; ++j)
{
cout << i;
//the above statement is for debugging purposes so that I can see
//which column easier
std::cout << grid[i][j].letter;
}
std::cout << std::endl;
}
cout << "1 2 3 4 5 6" << endl;
Now, the original goal was to have the default .letter value be '.'. But for some reason, when I tried to do this, there are disastrous results; the screen fills up with characters moving so fast I can't entirely see what they are (I recall some hearts and smiley faces), along with an obnoxious, rapid beeping. So I decided to leave that commented line out.
When I run the program without that line, for some reason, the "grid" always displays characters in certain spots, without any input from the user, or without me having expressly declared any values to that spot. For instance, the spot of the 1st column from the left and the bottom row, always has a character in it (grid[6][5].letter). It changes every time I run the program, and I've seen it range from a heart, to the letter A, to the spanish 'n' (the one with a ~ over it).
I thought to myself, "Hey, since grid[6][5] is the spots that are always buggy, I'll just declare those individual spot's .letter values to be blank (' ')!". That didn't work.
I've got no idea why this one spot is giving me trouble. There were other areas that would have an abnormal character, but I was able to neutralize them by setting their .letter values to blank. If anyone has any idea on how to fix this, pleas
EDIT: The other abnormal characters, which appear at grid[6][0], grid[6][1], grid[6][5], and grid[6][4], all make my program crash at later stages if I set them to blank (' '); however, blanking grid[6][5] is the one that makes it crash at the get go. I tried using a debugger, but it wasn't able to tell me anything helpful.

you're running over the end of your arrays
Tile grid [6][5]; needs to be Tile grid [7][6];
or you need to loop only to i < 6 and j < 5.

Related

How can I 'pan out' (make screen bytes smaller) of the console screen to render 2d pyramids larger?

I am using Windows 10 with code blocks to compile my code.
I wonder WHY you want to do that. This seems to be a typical homework assignment problem for practising loops and logic. That usually is restricted to numbers easily fitting on a console. Could you elaborate what causes the need to go beyond say a size of 30? – Yunnosch 10 hours ago
#Yunnosch For pure hypothetical and experimental reasons. I essentially have a dream I could write a program that renders massive 2d pyramids on a console screen, and maybe create some game out of it. I was hoping I could figure out a way to 'pan out' of the console screen thus making the screen bytes smaller. Somebody has to know more than me, and can lead me in the right direction to accomplishing this '2d pyramid rendering' program. Thanks in advance! – Fibonacci 3 mins ago
My goal is to be able to render massive pyramid structures onto a console output screen. The code here simply asks for a number of rows and prints out a pyramid. ex. drawPyramid(50);
#include <iostream> // include iostream
using namespace std; // include std
// Draw pyramid function here
void drawPyramid(int rows)
{
// initializes space and creates for loop to keep track of rows, I and k
int space;
for(int i = 1, k = 0; i <= rows; ++i, k=0)
{
// draws spaces required
for(space = 1; space <= rows-i; ++space)
{
cout << " ";
}
// draws matter
while(k != 2*i-1)
{
cout << "* ";
++k;
}
//prints new line based on rows
cout << endl;
}
}
//driver program
int main()
{
bool fTrue = false;
// loops until user presses '0'
while(!fTrue)
{
cout << "Press (0) to quit...\n";
int i,rows;
cout << "Enter number of rows: \n";
cin >> rows;
drawPyramid(rows); // draw function called
if(rows == 0)
{
fTrue = true;
}
}
return 0;
}
Output:
While the program works great I'd like to be able to pass in bigger values such as drawPyramid(500); or drawPyramid(1000); anything above the value 50 produces results like so.
Results:
Hopefully you can understand what I am trying to ask. I want to be able to 'pan out' and move the asterisks closer together so that I can pass in larger input values into the drawPyramid() function... Thanks in advance!
I am using Windows 10 with code blocks to compile my code.

How would I overwrite a printed 2D array to simulate 'updates'

So given a 2D array called 'world' and the code below to output the array to the console. I want to constantly update the outputted array using a while loop to simulate movement and other actions via changes in the array values without it messily reprinting the entire thing for every update.
I would imagine the best way to do this would be to try and reset the output stream to the first line and overwrite the previous printed array each update but I am unsure on how to do this.
char world[20][20];
for (unsigned int row = 0; row < std::size(world); row++)
{
for (unsigned int col = 0; col < std::size(world); col++)
{
std::cout << world[row][col];
}
std::cout << std::endl;
}
There is a simple way to do this on one line, using \r with printf, as discussed here. However, I'm not certain this is easy if one wishes to reprint multiple lines, as you do.
A better suggestion would be to make use of something like ncurses, which seems to be designed for your purposes, and was probably used to make other programs you've seen operate this way.

C++ character variable value of '\x1'

I'm failing to understand why would the loop exit at the value of character variable i = '\x1'
#include <iostream>
using namespace std;
int main()
{
char i;
for (i = 1; i < 10, i++;)
{
cout << i << endl;
}
return 0;
}
Can somebody please explain this behavior ?
This is wrong
for (i = 1; i < 10, i++;)
/* ^ should be ; */
You only declared 3 regions for the loop, but put your increment statement in the middle area, and left your increment area empty. I have no idea which statement in the middle area your compiler will choose to execute. Best not to try to be cute and deceive your compiler. Let alone some colleague who will read your code years from now and go WTF???
A for loop has 3 distinct areas delimited by semi-colons:
The initialization area. You can declare as many variables in here as you want. These can be delimited by commas.
The test area. This is where an expression goes to test if the loop should continue.
The post loop area. This region of code gets executed after every loop.
Try to keep it simple. If it is going to be more complicated then use a while loop.
The reason that i ends up being 1 is that when i++ is zero, which terminates the loop, then i will become 1 (That is what the form of the ++ operator you used does). As the other answered have pointed out, once you fix your code by moving i++ out of the condition by replacing the comma with a semicolon, then i will make it all the way to 10 as desired.
for (i = 1; i < 10; i++)
You wrote for statement wrong.

OpenCV program crash when modifying array?

I'm trying to find the boundary of a sequence of nonzeroes in a row matrix starting from the maximum point and then setting the values outside the boundary to zero.
for(int i=maxloc.x; i < 280 ; i++){
if(!foundBound && sum_r.at<uchar>(0,i) == 0){
foundBound=true;
bb.rightEdge = i;
}
else if(foundBound){
cout << i << endl;
sum_r.at<uchar>(0,i) = 0; <--- offending line
}
}
But the program crashes when I run it. If I comment out sum_r.at<uchar>(0,i) = 0; then the program runs fine until the end. I also got a insufficent memory error once but I can't replicate it. Is there also a better way of accessing the individual elements of a Mat?
The program crash indicates that you are probably going outside the boundaries of your matrix. Check the following:
maxloc.x < 280
sum_r.cols == 280

Do I need more space?

I have code that is supposed to separate a string into 3 length sections:
ABCDEFG should be ABC DEF G
However, I have an extremely long string and I keep getting the
terminate called without an active exception
When I cut the length of the string down, it seems to work. Do I need more space? I thought when using a string I didn't have to worry about space.
int main ()
{
string code, default_Code, start_C;
default_Code = "TCAATGTAACGCGCTACCCGGAGCTCTGGGCCCAAATTTCATCCACT";
start_C = "AUG";
code = default_Code;
for (double j = 0; j < code.length(); j++) { //insert spacing here
code.insert(j += 3, 1, ' ');
}
cout << code;
return 0;
}
Think about the case when code.length() == 2. You're inserting a space somewhere over the string. I'm not sure but it would be okay if for(int j=0; j+3 < code.length(); j++).
This is some fairly confusing code. You are looping through a string and looping until you reach the end of the string. However, inside the loop you are not only modifying the string you are looping through, but you also change the loop variable when you say j += 3.
It happens to work for any string with a multiple of 3 letters, but you are not correctly handling other cases.
Here is a working example of the for loop that is a bit more clear it what it's doing:
// We skip 4 each time because we added a space.
for (int j = 3; j < code.length(); j += 4)
{
code.insert(j, 1, ' ');
}
You are using an extremely inefficient method to do such an operation. Every time you insert a space you are moving all the remaining part of the string forward and this means that the total number of operations you will need is in the order of o(n**2).
You can instead do this transormation with a single o(n) pass by using a read-write approach:
// input string is assumed to be non-empty
std::string new_string((old_string.size()*4-1)/3);
int writeptr = 0, count = 0;
for (int readptr=0,n=old_string.size(); readptr<n; readptr++) {
new_string[writeptr++] = old_string[readptr];
if (++count == 3) {
count = 0;
new_string[writeptr++] = ' ';
}
}
A similar algorithm can be written also to work "inplace" instead of creating a new string, simply you have to first enlarge the string and then work backward.
Note also that while it's true that for a string you don't need to care about allocation and deallocation still there are limits about the size of a string object (even if probably you are not hitting them... your version is so slow that it would take forever to get to that point on a modern computer).