简体   繁体   中英

why does cout.tellp always return -1?

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?

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM