Reputation: 1897
So I'm trying to print out a table nicely with even padding like so:
int rowLength = 8 * 4 + 8 + 1;
char arr[rowLength];
fill(arr, arr + rowLength, '-');
string divider = arr;
for(int y = 0; y < 5; y++) {
cout << "\n" << divider << "\n";
for(int x = 0; x < 8; x++) {
cout << "| " << "1";
if(x == 7)
cout << "|";
}
}
cout << "\n" << divider;
And I'm expecting the table to print evenly, however it prints as follows:
Does anyone know how I can fix the print code, so it evenly prints and without the 2h at the end?
Thanks!
Upvotes: 0
Views: 125
Reputation: 118445
string divider = arr;
This std::string
gets constructed from arr
, which is a char
array that gets decayed to a char *
. When constructing from a char *
, the char *
must be a null-terminated string.
Your code fills the entire char
array with characters, but fails to append an additional '\0'
byte. This results in undefined behavior.
Upvotes: 5