发生这种情况是因为它们已经改变颜色并向后打印(从右到左).
这是一个错误,错误的代码,我的系统上的错误设置或(我怀疑它)它应该是什么样的?
#include <Windows.h> #include <iostream> void moveTo(int x,int y){ COORD kord={x,y}; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),kord); } void setColor(WORD attributes){ SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),attributes); } void main(){ for(int i=9;i+1;i--) { moveTo(i,0); std::cout.put('X'); } for(int i=-10;i;i++) { moveTo(i+10,1); std::cout.put('X'); } setColor(8); for(int i=9;i+1;i--) { moveTo(i,2); std::cout.put('X'); } for(int i=-10;i;i++) { moveTo(i+10,3); std::cout.put('X'); } setColor(7); for(int i=9;i+1;i--) { moveTo(i,4); std::cout.put('X'); } for(int i=-10;i;i++) { moveTo(i+10,5); std::cout.put('X'); } std::cin.get(); }
解决方法
如Hans Passant勘误表中所述:
I repro too,VS2008 on Win7. Cool bug. Changing the console font fixes it.
让我们使用这个bug隔离.我将此字体识别为Petite Terminal,这意味着您最有可能将此项目配置为Win32控制台应用程序. GCC的额外repro确认了这一假设,从实际角度来看,我们将假设你们所有人都在Windows终端内部运行32位控制台应用程序.
问题变成了为什么它在默认终端字体,颜色8和向后写入console screen buffer.的上下文中正好写了一个额外的像素列
具体来说,让我们将这个问题分解为其组成部分:
>发出写入时,会将字符写入终端阵列中的某个位置
>选择默认颜色(7)时,像素不会溢出到阵列中的其他缓冲区
>选择颜色8时,会将另一列像素写入缓冲区的下一个区域,只有在向后背诵文本时才能看到
由于(3)中存在溢出,这是一个错误.
Quoting Raymond Chen:
The console rendering model assumes each character fits neatly inside
its fixed-sized cell. When a new character is written to a cell,the
old cell is overprinted with the new character,but if the old
character has overhang or underhang,those extra pixels are left
behind since they “spilled over” the required cell and infected
neighbor cells. Similarly,if a neighboring character “spilled over”,
those “spillover pixels” would get erased.The set of fonts that could be used in the console window was trimmed
to the fonts that were tested and known to work acceptably in console
windows. For English systems,this brought us down to Lucida Console
and Terminal.…
“Well,that’s stupid. You should’ve stopped me from choosing a font
that so clearly results in nonsense.”And that’s what we did.
并不是说我把雷蒙德归咎于雷蒙德,但他权威地将此描述为“不可能发生”.
Windows的控制台字体的选择和测试应该已经抓住了这一点.事实上它甚至是一个问题都是一种失常.