printing char arry to console

Oct 8, 2011 at 8:49am
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.
Oct 8, 2011 at 8:51am
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 Oct 8, 2011 at 8:51am
Oct 8, 2011 at 12:14pm
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 Oct 8, 2011 at 12:14pm
Oct 8, 2011 at 3:21pm
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 Oct 8, 2011 at 4:30pm
Topic archived. No new replies allowed.