简体   繁体   中英

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++?

If you are referring something similar to the Console stdout (C++), eg cout, You can use either this:

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

or the iomanip library allows you to have a number of text formatting capabilities. For example:

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

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

Don't forget to #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.

For more complex cases, have a look at curses, a comprehensive library for terminal programming.

In most common Unix-alike platforms you can use the ioctl system call:

#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.

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 . (Windows consoles provide an analogous interface, with different details -- since no system was specified, POSIX is what most people assume).

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 .
  • 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 ).
  • move the cursor to cell W - L on the current row of the screen (counting from zero).
  • 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? . (Some systems support a similar call with the TIOCGSIZE symbol, as noted in Getting terminal width in 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). Not recommended but documentation is available, eg, in Linux's console_codes manual page, or XTerm Control Sequences . This sequence was not in the VT100, upon which many terminal emulators were based, but documented in ISO-6429. XTerm added it in 1997 (no documentation exists for that era in 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 ). Supposing that the terminal supports HPA , your program would do something like

    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:

    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:

#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.

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