0

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

4
  • Does it have to not contain a null at the end of the array? Commented Oct 26, 2012 at 2:41
  • @chris nulls are string terminators. No strings here. Commented Oct 26, 2012 at 2:59
  • @SethBattin, Char arrays in C and C++ are typically null-terminated. I took the string referred to as std::string. Commented Oct 26, 2012 at 3:07
  • @chris Regardless, this operation does not require them. Although simonarame's implementation wisely checks for them anyway, since the objects are constructed from strings. Which should, yes, contain null terminators. :) Commented Oct 26, 2012 at 3:28

2 Answers 2

2

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));
Sign up to request clarification or add additional context in comments.

Comments

0
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;
 }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.