Question

How to implement ostream-like class from scratch using printf only?
For me looks like the problem is in choosing the format string ,which is actually equal to the identifying input`s type and treating precision

Was it helpful?

Solution

I assume you mean something that overloads operator<< by "an ostream-like class". It's easy to identify the type of the argument to a function just by having overloads. For example, you might have:

ostreamlike& ostreamlike::operator<<(int x)
{
  printf("%d", x);
  return *this;
}

ostreamlike& ostreamlike::operator<<(float x)
{
  printf("%f", x);
  return *this;
}

The format of the output is determined by whichever overload is picked.

OTHER TIPS

Think, it could be something like that

#include <stdio.h>

class ostreamlike {
public:
  ostreamlike(FILE* f_): f(f_) {}

  ostreamlike& write(int n) {
    fprintf(f, "%d", n);
    return *this;
  }

  ostreamlike& write(const char* n) {
    fprintf(f, "%s", n);
    return *this;
  }

private:
  FILE* f;
};

// operator for types that is supported ostreamlike internally
template <typename type>
ostreamlike& operator<<(ostreamlike& stream, const type& data) {
  return stream.write(data);
}

// external implementations to write using ostreamlike
ostreamlike& operator<<(ostreamlike& stream, bool data) {
  return stream.write(data ? "true" : "false");
}

int main() {
  ostreamlike s(stdout);
  s << "hello " << 1 << " : " << true << "\n";
  return 0;
}

It depends on how close to the real ostream you want to be. Assuming you want to do it properly you would also need a streambuf derived class. ostream only does the formatting, the actual I/O is done by an internal streambuf derived class. Since streambuf does unformatted I/O you would need to use fwrite not printf.

If your goal is just to do I/O on an already existing FILE* pointer this is the way to go. You derive one class from streambuf, say streambuf_with_FILE and then you derive another class from ostream say ostream_with_FILE. streambuf_with_FILE overrides the appropriate methods to do the actual I/O and ostream_with_FILE has an internal streambuf_with_FILE object. There's actually very little code required.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top