Reputation: 175
Say I have a char array: Char[3] which contains a,b,c.
What would be the easiest way to print Char as "abc" without using any of the c++ string libraries.
I am trying to overload the << operator so that i can print a class obj that contains a char array back as the original string that the obj was made with.
I am confused as to how to implement the solutions provided.
my word objs can be used like this:
Word.length() returns how long it is Word[XXX] will return whats at index XXX
Upvotes: 0
Views: 570
Reputation: 375
class OverloadedCharArrayClass {
public:
char* chars;
friend ostream& operator<<(ostream& os, const OverloadedCharArrayClass& charArray){
int i=0;
while(charArray.chars[i]!='\0'){
os<<charArray.chars[i];
i++;
}
return os;
}
}
Upvotes: 0
Reputation: 476950
Try copy
:
#include <algorithm>
#include <iterator>
#include <iostream>
char data[3] = { 'a', 'b', 'c' };
std::copy(data, data + sizeof data, std::ostream_iterator<char>(std::cout));
Upvotes: 2