简体   繁体   English

为什么cout.tellp总是返回-1?

[英]why does cout.tellp always return -1?

I want to provide a tab-like capability for C++ text output streams. 我想为C ++文本输出流提供类似标签的功能。 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". 该功能应该允许我说“注意这个位置”,然后允许多个插入操作,最后允许我说“添加足够的填充字符,以便在最初指出的位置之后结束N字符”。

The standard iostream system does not seem to maintain a column position but I had thought that I could fake it using tellp() . 标准的iostream系统似乎没有保持列位置,但我原以为我可以使用tellp()伪造它。 My assumption was that the difference between tellp() at two points in my output sequence would correspond to the number of intervening bytes. 我的假设是,输出序列中两点的tellp()之间的差异将对应于插入字节的数量。

Unfortunately, at least in my Gnu C++ environment, cout does not maintain the fiction of a stream position. 不幸的是,至少在我的Gnu C ++环境中, cout并没有保持流位置的虚构。 Every cout.tellp() call returns -1 . 每个cout.tellp()调用都returns -1 Why is that? 这是为什么?

tellp returns a position in a stream so that you can seek to it. tellp返回流中的位置,以便您可以查找它。 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. 如果您想在屏幕上进行合理的光标定位,请查看随附的ANSI终端规范和转义命令。 They allow for cursor position discovery and placement. 它们允许光标位置发现和放置。

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

In general, the screen is not a stream. 通常,屏幕不是流。 Neither is the keyboard, for that matter :) 也不是键盘,就此而言:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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