Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does cout.tellp always return -1?

Tags:

c++

iostream

cout

I want to provide a tab-like capability for C++ text output streams. The feature should allow me to say "note this position", then allow multiple insert operations, and finally allow me to say "add enough fill characters so as to end up N characters past the originally noted position".

The standard iostream system does not seem to maintain a column position but I had thought that I could fake it using tellp(). My assumption was that the difference between tellp() at two points in my output sequence would correspond to the number of intervening bytes.

Unfortunately, at least in my Gnu C++ environment, cout does not maintain the fiction of a stream position. Every cout.tellp() call returns -1. Why is that?

like image 917
John Yates Avatar asked Jun 23 '12 02:06

John Yates


1 Answers

tellp returns a position in a stream so that you can seek to it. Console does not allow seeking. Besides, even you interpret position as "the number of bytes written to the stream since it was created", that number won't be of any use for cursor positioning - the screen wraps around, its width is generally unpredictable. You just won't know what column you're on, since the row length is variable.

If you want reasonable cursor positioning on the screen, check out the ANSI terminal specification and escape commands that come with it. They allow for cursor position discovery and placement.

http://ascii-table.com/ansi-escape-sequences.php

In general, the screen is not a stream. Neither is the keyboard, for that matter :)

like image 197
Seva Alekseyev Avatar answered Oct 14 '22 17:10

Seva Alekseyev