printing char arry to console

Hello i am totally new to C++ but i have some experience with Java and C#. So can someone please explain to me why when i run this:

1
2
3
4
5
6
7
8
9
#include "stdafx.h"
#include <iostream>
using namespace std;
	
int main(){
	char a[3]={'a','b','c'};
	cout<<a<<endl;
	return 0;
}


i am getting:
abcyΦk£‡ρ

instead of:
abc


note that every time i run this, the characters after "abc" vary.
The << operator expects char arrays to be zero terminated. Try:
1
2
3
4
5
6
7
8
#include <iostream>
using namespace std;
	
int main(){
	char a[4]={'a','b','c','\0'};
	cout<<a<<endl;
	return 0;
}
Last edited on
Arrays are friends with loops. Here is your code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14

#include "stdafx.h"
#include <iostream>
using namespace std;
	
int main(){
	char a[3]={'a','b','c'};
	for(int i = 0; i <= 3; i++){
            
	cout<<a[i]<<endl;
}
system("PAUSE");
	return 0;
}


Always use loops for array string displays or numbers...
Last edited on
Duh... know i remember i read about the '\0' somewhere. Thank you for your reply, i was going nuts trying to figure that out.

Happykiller thanx for your reply too.
Last edited on
Topic archived. No new replies allowed.