Why this garbage character after cout?

Hello, I tried the below in two different compilers (Visual Studio and gdb online). Any idea why I am getting the garbage characters after printing "December 31" and how can I fix this? Thanks.

February 29
March 31
April 30
May 31
June 30
July 31
August 30
September 31
October 30
November 30
December 31
╠╠╠╠╠╠╠╠└YÄ -858993460


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/******************************************************************************

                              Online C++ Compiler.
               Code, Compile, Run and Debug C++ program online.
Write your code in this editor and press "Run" button to compile and execute it.

*******************************************************************************/

#include <iostream>
#include <sstream>


int main()
{

	//Define arrays type char representing the month name and how many days on each month
	char array_char[12][20] = { "January", "February" ,"March", "April", "May", "June", "July"
							 , "August", "September", "October", "November", "December" };
	int array_days[12] = { 30, 29, 31, 30, 31, 30, 31, 30, 31, 30, 30, 31 };

	std::stringstream mychar;

	for (int i = 1; i < 13; i++) {
		mychar << array_char[i] << " ";
		mychar << array_days[i] << "\n";
	}

	std::cout << mychar.str();  //<== Garbage characters here
 
}
Because an array of dimension 12 has indices 0-11, not 12 as your loop implies.
Probably being caused by overflowing your array during the "read" loop.

Remember arrays start at zero and stop at size - 1.



Wow. Let's see: the subscript "12" means it must start at "0"... therefore it goes from 0 to 11. My intention was to allow up to 12 elements in this array, but starting at 1. Well so it means I have to do array_days[13] then... very interesting. Thank you!
Well, you could:
- loop for i=0; i < 12 with your existing arrays; or
- define arrays of size 1+12 but remember to start them with blanks/zeros; or
- use range-based loops and iterate through them instead.

Personally, for calendar-based things like this I'd do the middle one, but it's your code.

BTW - some of your months have a rather odd number of days in them.
Last edited on
Very good. Thank you!
Topic archived. No new replies allowed.