简体   繁体   English

如何从屏幕右侧而不是 C 中通常的左侧按 output 进行打印?

[英]How to print by output from the right hand side of the screen instead of the usual left hand side in C?

I am programming a game in which I need to create some blocks.我正在编写一个游戏,我需要在其中创建一些块。 I programmed that part perfectly, but the problem is that they need to aligned towards the right hand side of the screen as opposed to the usual left hand side.我对该部分进行了完美编程,但问题是它们需要与屏幕的右侧对齐,而不是通常的左侧。 Now, I know the long approach of printing blanks to do so, but I was just curious if there is any shortcut to print the output from the right in C or C++?现在,我知道打印空白的漫长方法,但我只是好奇是否有任何快捷方式可以从 C 或 C++ 的右侧打印 output?

If you are referring something similar to the Console stdout (C++), eg cout, You can use either this: 如果要引用类似于Console stdout(C ++)的名称,例如cout,则可以使用以下任一方法:

http://www.cplusplus.com/reference/ios/right/ http://www.cplusplus.com/reference/ios/right/

or the iomanip library allows you to have a number of text formatting capabilities. 或iomanip库允许您具有多种文本格式设置功能。 For example: 例如:

cout << setw(20) << setiosflags(ios::right) << "Hello World!" << endl;

http://www.cplusplus.com/reference/iomanip/ http://www.cplusplus.com/reference/iomanip/

Don't forget to #include <iomanip> . 不要忘记#include <iomanip>

Oh and please note that to align right, I believe you have to set width. 哦,请注意,要正确对齐,我相信您必须设置宽度。

Hope it helps. 希望能帮助到你。

First, figure out how many columns the screen has. 首先,找出屏幕上有多少列。 This depends on the platform you are programming for; 这取决于您要为其编程的平台。 I cannot help you because you did not specify the platform. 我没有帮助您,因为您没有指定平台。

For the actual printing, you can use printf with a field-width specifier which right-aligns your text to the given field-width. 对于实际的打印,您可以将printf字段宽度说明符配合使用,该说明符会将您的文本右对齐到给定的字段宽度。

For more complex cases, have a look at curses, a comprehensive library for terminal programming. 对于更复杂的情况,请查看curses,这是一个用于终端编程的综合库。

In most common Unix-alike platforms you can use the ioctl system call: 在最常见的类似Unix的平台上,可以使用ioctl系统调用:

#include <sys/ioctl.h>
#include <stdio.h>

int main()
{
    char *string = "Hello World";
    struct winsize w; 

    ioctl(0, TIOCGWINSZ, &w);
    printf("%*s\n", w.ws_col, string);
    return 0;
}

As noted in other suggested answers, the solution really depends on the type of system on which the program runs, and more importantly what type of device which displays the result. 如其他建议的答案所述,解决方案实际上取决于程序在其上运行的系统的类型,更重要的是取决于显示结果的设备的类型。 The variations on alignment using formatting controls (as with printf or cout) are essentially the same as padding the output line yourself with blanks, but using a more elegant programming interface. 使用格式控制(如printf或cout)的对齐方式的变化与使用空白填充自己的输出行基本相同,但使用的是更优雅的编程界面。

Moving past those (since they do not appear to be what was requested), the type of display device is of interest. 越过那些(因为它们似乎不是所请求的),因此显示设备的类型是令人关注的。 Graphical displays universally permit one to place text anywhere on the (programmable) device. 图形显示普遍允许人们将文本放置在(可编程)设备上的任何位置。 However, character-cell devices such as a terminal make it a little harder. 但是,字符单元设备(例如终端)使其变得更难一点。 Any that you are likely to use on a POSIX system allow you to write text at the cursor position, and to change the position at which you write the text using cursor-addressing . 您可能在POSIX系统上使用的任何工具都允许您在光标位置写文本,并使用cursor-addressing更改您写文本的位置。 (Windows consoles provide an analogous interface, with different details -- since no system was specified, POSIX is what most people assume). (Windows控制台提供了类似的界面,但具有不同的细节-由于未指定系统,因此大多数人都认为POSIX是必需的)。

With cursor-addressing, you could write a given string aligned at the right side of the screen by doing this: 使用游标寻址,您可以通过以下操作编写一个在屏幕右侧对齐的给定字符串:

  • find the width of the screen, call that W . 找到屏幕的宽度,称为W
  • find the length of the string, call that L (actually you need the number of cells on the screen which it will use -- the length of a UTF-8 string in bytes differs from its width ). 找到字符串的长度,调用L (实际上,您需要它在屏幕上使用的单元格数量-以字节为单位的UTF-8字符串的长度与其宽度不同)。
  • move the cursor to cell W - L on the current row of the screen (counting from zero). 光标移动到屏幕当前行上的单元格W - L (从零开始计数)。
  • write the text on the screen 在屏幕上写文字

Though not part of POSIX , the TIOCGWINSZ feature is widely supported, and provides a way to get the screen width, eg, How to set the terminal's size? 尽管不是POSIX的一部分,但TIOCGWINSZ功能得到了广泛支持,并提供了一种获取屏幕宽度的方法,例如, 如何设置终端的尺寸? . (Some systems support a similar call with the TIOCGSIZE symbol, as noted in Getting terminal width in C? ). (某些系统使用TIOCGSIZE符号支持类似的调用,如在C获取终端宽度中所述 )。

Rather than move the cursor along the line by writing blanks, one may choose fewer characters in a control sequence . 与其通过写空格沿行移动光标,不如在控制序列中选择更少的字符。 For moving the cursor, there are choices: 要移动光标,有以下选择:

  • hard-code a control sequence such as the one for HPA (horizontal position, absolute). 硬编码诸如HPA的控制序列(水平位置,绝对值)。 Not recommended but documentation is available, eg, in Linux's console_codes manual page, or XTerm Control Sequences . 不推荐使用,但是可以找到文档,例如,在Linux的console_codes手册页或XTerm Control Sequences中 This sequence was not in the VT100, upon which many terminal emulators were based, but documented in ISO-6429. 该序列不在许多终端仿真器所基于的VT100中,而是记录在ISO-6429中。 XTerm added it in 1997 (no documentation exists for that era in Linux). XTerm在1997年添加了它(在Linux中没有那个时代的文档)。
  • use termcap to ask if the terminal supports HPA (called "ch" in termcaps) or use CUF (cursor-forward) with a parameter (but that requires you to know where you are ). 使用termcap询问终端是否支持HPA (在termcaps中称为"ch" )或使用带有参数的CUF (光标向前)(但这要求您知道您的位置 )。 Supposing that the terminal supports HPA , your program would do something like 假设终端支持HPA ,您的程序将执行以下操作

    char *hpa = tgetstr("cm", &areap); tgoto(hpa, W - L, 0); puts(mystring);

  • use curses , and let it decide how to go to the right place: 使用curses ,让它决定如何去正确的地方:

    int y, x; getyx(stdscr, y, x); move(y, WL); addstr(mystring);

the following, some of the info found at: <http://wiki.bash-hackers.org/scripting/terminalcodes>
should greatly help you with handling the screen/cursor activities.

General useful ASCII codes

The Ctrl-Key representation is simply associating the non-printable characters from ASCII code 1 with the printable (letter) characters from ASCII code 65 ("A"). ASCII code 1 would be ^A (Ctrl-A), while ASCII code 7 (BEL) would be ^G (Ctrl-G). This is a common representation (and input method) and historically comes from one of the VT series of terminals.
Name    decimal octal   hex C-escape    Ctrl-Key    Description
BEL 7   007 0x07    \a  ^G  Terminal bell
BS  8   010 0x08    \b  ^H  Backspace
HT  9   011 0x09    \t  ^I  Horizontal TAB
LF  10  012 0x0A    \n  ^J  Linefeed (newline)
VT  11  013 0x0B    \v  ^K  Vertical TAB
FF  12  014 0x0C    \f  ^L  Formfeed (also: New page NP)
CR  13  015 0x0D    \r  ^M  Carriage return
ESC 27  033 0x1B    <none>  ^[  Escape character
DEL 127 177 0x7F    <none>  <none>  Delete character
Cursor handling
ANSI    terminfo equivalent Description
[ <X> ; <Y> H
[ <X> ; <Y> f   cup <X> <Y> Home-positioning to X and Y coordinates
:!: it seems that ANSI takes 1-1 as root while tput takes 0-0
[ H home    Home-positioning to root (0-0)
7   sc  Save current cursor position
8   rc  Restore current cursor position
:?: most likely a normal code like \b   cub1    move left one space (backspace)
VT100 [ ? 25 l  civis   switch cursor invisible
VT100 [ ? 25 h  cvvis   switch cursor visible
Erasing text
ANSI    terminfo equivalent     Description
[ K
[ 0 K   el  Clear line from current cursor position to end of line
[ 1 K   el1     Clear line from beginning to current cursor position
[ 2 K   el2:?:  Clear whole line (cursor position unchanged)
General text attributes
ANSI    terminfo equivalent Description
[ 0 m   sgr0    Reset all attributes
[ 1 m   bold    Set "bright" attribute
[ 2 m   dim Set "dim" attribute
[ 4 m   set smul unset rmul :?: Set "underscore" (underlined text) attribute
[ 5 m   blink   Set "blink" attribute
[ 7 m   rev Set "reverse" attribute
[ 8 m   invis   Set "hidden" attribute
Foreground coloring
ANSI    terminfo equivalent     Description
[ 3 0 m     setaf 0     Set foreground to color #0 - black
[ 3 1 m     setaf 1     Set foreground to color #1 - red
[ 3 2 m     setaf 2     Set foreground to color #2 - green
[ 3 3 m     setaf 3     Set foreground to color #3 - yellow
[ 3 4 m     setaf 4     Set foreground to color #4 - blue
[ 3 5 m     setaf 5     Set foreground to color #5 - magenta
[ 3 6 m     setaf 6     Set foreground to color #6 - cyan
[ 3 7 m     setaf 7     Set foreground to color #7 - white
[ 3 9 m     setaf 9     Set default color as foreground color
Background coloring
ANSI    terminfo equivalent     Description
[ 4 0 m     setab 0     Set background to color #0 - black
[ 4 1 m     setab 1     Set background to color #1 - red
[ 4 2 m     setab 2     Set background to color #2 - green
[ 4 3 m     setab 3     Set background to color #3 - yellow
[ 4 4 m     setab 4     Set background to color #4 - blue
[ 4 5 m     setab 5     Set background to color #5 - magenta
[ 4 6 m     setab 6     Set background to color #6 - cyan
[ 4 7 m     setab 7     Set background to color #7 - white
[ 4 9 m     setaf 9     Set default color as background color
Misc codes
Save/restore screen

Used capabilities: smcup, rmcup

You've undoubtedly already encountered programs that restore the terminal contents after they do their work (like vim). This can be done by the following commands:

# save, clear screen
tput smcup
clear

# example "application" follows...
read -n1 -p "Press any key to continue..."
# example "application" ends here

# restore
tput rmcup

These features require that certain capabilities exist in your termcap/terminfo. While xterm and most of its clones (rxvt, urxvt, etc) will support the instructions, your operating system may not include references to them in its default xterm profile. (FreeBSD, in particular, falls into this category.) If `tput smcup` appears to do nothing for you, and you don't want to modify your system termcap/terminfo data, and you KNOW that you are using a compatible xterm application, the following may be work for you:

echo -e '\033[?47h' # save screen
echo -e '\033[?47l' # restore screen


The following is more specific to cursor placement:
<http://tldp.org/HOWTO/Bash-Prompt-HOWTO/x361.html>

- Position the Cursor:
  \033[<L>;<C>H
     Or
  \033[<L>;<C>f
  puts the cursor at line L and column C.
- Move the cursor up N lines:
  \033[<N>A
- Move the cursor down N lines:
  \033[<N>B
- Move the cursor forward N columns:
  \033[<N>C
- Move the cursor backward N columns:
  \033[<N>D

- Clear the screen, move to (0,0):
  \033[2J
- Erase to end of line:
  \033[K

- Save cursor position:
  \033[s
- Restore cursor position:
  \033[u

Lets say that we are trying to print '*' from the right.And in total we want to print 10 stars.For better visualization I will be using Sleep(1000)to see the printing of the stars in action.Here's what the sample program will look like:假设我们正在尝试从右侧打印“*”。我们总共要打印 10 颗星。为了更好地可视化,我将使用 Sleep(1000) 来查看正在打印的星星。这是示例程序将如下所示:

#include<iostream>
#include<iomanip>
#include<Windows.h>

using namespace std;

int main() {    
    
    
    int n=10;
    for(int i=n;i>0;i--){

        cout<<setw(i+1)<<"*\r"<<flush;
        Sleep(1000);
    }
    return 0;
   
}

Here the setw() function from the "iomanip" library is used to set the width of the string to be printed.The additional "+1" in "i+1" is used to account for the character "\r" which is an escape character in c++ called the "carriage return" which tells the terminal emulator to move the cursor to the start of the line, not to the next line, like \n.这里使用“iomanip”库中的 setw() function 来设置要打印的字符串的宽度。“i+1”中的附加“+1”用于说明字符“\r”,即c++ 中的转义字符称为“回车”,它告诉终端仿真器将 cursor 移动到行的开头,而不是下一行,例如 \n。

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

相关问题 从右手到左手如何使用substr? 如何将每8个字符从字符串转换为int? - How to use substr from right hand side to left hand side? How to convert each 8 characters from a string to an int? 如何在左右两侧创建运算符*(double)以进行相乘? - How to create operator*(double) for multiplying on both the left and right hand side? C ++容器和右侧 - C++ Containers and right hand side 如何在C ++中从右侧使用substr获取字符串 - how to use substr get string from right hand side in c++ 如何在文本的左侧和右侧用空格填充字符数组 - How to pad char array with empty spaces on left and right hand side of the text 如何在最右侧的标题栏中添加“全屏”按钮? - How to add the “full screen” button to the title bar on the far right hand side? 与赋值表达式的C ++比较是右侧表达式 - C++ comparison with an assignment expression be the right hand side expression 在分配的右侧使用减量运算符是否有效的C ++? - Is using a predecrement operator on the right hand side of an assignment valid C++? 如何防止赋值运算符左侧的临时 - How to prevent a temporary on the left hand side of the assignment operator 如何在 rtl 对齐中打开右侧的子菜单? - How to open sub-menu on right hand side in rtl alignments?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM