chowey
chowey

Reputation: 9836

Write to stdout using character array (not null terminated) c/c++

What's the most straightforward way to write to stdout using a character array? I want to output a slice of a much larger array, and the slice is not null-terminated. I want to avoid copying the slice to a "proper" null-terminated c-string.

Upvotes: 9

Views: 4314

Answers (5)

Pierre Fourgeaud
Pierre Fourgeaud

Reputation: 14510

std::copy seems to exactly do what you want :

#include <iostream>    // for std::cout
#include <algorithm>   // for std::copy
#include <iterator>    // for std::ostream_iterator

//...
char arr[] = "abcdefij";

std::copy(arr + 2, arr + 5, std::ostream_iterator<char>(std::cout, ""));

This example will write on the standard output: cde.

Here is a live example.

Upvotes: 4

Mats Petersson
Mats Petersson

Reputation: 129454

Ok, this is the "department for silly ideas":

 class partial_print_wrapper
 {
   private:
     const char *str;
     int start;
     int end;
   public:
     partial_print_wrapper(const char *s, int st, int en) : str(s), start(st), end(en) {}
     friend ostream& operator <<(ostream &os, const partial_print_wrapper& pw);
 };

 ostream& operator <<(ostream &os, const partial_print_wrapper& pw)
 {
     for(int i = pw.start; i < pw.end; i++)
     {
         os << pw.str[i];
     }
     return os;
 }

 char *s = "Something quite long";

 cout << print_string_wrapper(s, 3, 8) << endl;

Upvotes: 1

Appleshell
Appleshell

Reputation: 7388

ostream::write should work.

#include <iostream>
int main() {
    char a[] = "ABCDEFGHIJ";
    std::ostream out(std::cout.rdbuf());
    out.write(a, 2);
}

Edit

Creating a separate ostream object is not required, as std::cout is a ostream object itself. So std::cout.write is sufficient.

Upvotes: 1

pippin1289
pippin1289

Reputation: 4939

If you know the bounds of the character array then you could write:

char* arr = new char[N];
for(size_t i = min_indx; i < max_indx; ++i) {
  cout << arr[i];
}

You just have to make sure min_indx is between 0 and N-1 and max_indx is between 0 and N.

Since we all like library functions to do things, here is the way to do it using std::copy:

copy(arr + min_indx, arr + max_indx, ostream_iterator<char>(cout, ""));

Upvotes: 1

chowey
chowey

Reputation: 9836

There is a pretty obvious solution I didn't find at first. std::cout is an instance of ostream.

void WriteChunk(char *buffer, size_t startpos, size_t length) {
    std::cout.write(buffer + startpos, length);
}

so std::cout.write does the trick.

Upvotes: 14

Related Questions