I've been working on a project in which the output should be this:
oo
oo
oo
###############
So I want the ground (#####...) to output before the 'o', but using std::cout, this doesn't seem to work, because it goes from top to bottom. Is there any method I could use to fix this, or maybe a different outputting method?
So upon further research, it can be done, but it's operating system specific.
The example I found is:
#include <iostream>
#include <windows.h> //This is where you will get the SetConsolePosition and
Coords struct
int main (void) {
COORD coord;
coord.X = 10;
coord.Y = 1;
std::cout << "Hello!" << std::endl;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
std::cout << "World!?" ;
return 0;
}
cout is what it is. It's a standard stream, which works on First In - First Out (FIFO) principle. So text that you print first, will be printed first, then text will be scrolled up, to provide space for next line. To output at specified coordinates of screen you need to change position where next character will be placed. How to do so, depends on what type of terminal\console you use, including what OS it is (on Linux , there are terminal types that do not support it or do not support it fully).
Check answers here: Linux drawing in text mode(no gui, desktop)
Okay, then you can add the below code in your code before your texts which are printing.
cout<<"################\n";
cout<<"oo\n";
cout<<" oo\n";
cout<<" oo\n";
Complete code:
#include
using namespace std;
int main() {
cout<<"################\n";
cout<<"oo\n";
cout<<" oo\n";
cout<<" oo\n";
return 0;
}
Output:
Related
I am teaching myself C++ and currently run the latest Fedora.
On a Windows command prompt you can address the screen location.
I am led to the believe that a Linux command terminal works, effectively, like characters printed to a piece of paper. i.e. You can't go "up" from where you are.
However, when you install in Linux, there is a progress bar (in text) which doesn't appear to print a new line each time with the increase of progress.
Also, take for example raspbi-config in which you can tab/arrow up and down a "menu" and select "OK" and "Cancel" etc.
How does one achieve this?
Can this then be used to do simple text graphics applications in Linux like one can do under Windows?
Any help would be appreciated.
Uberlinc.
Coding in C++.
General non-gui apps which simply "cout" to the stdout.
Only found one or two examples which show a progress bar that prints out to the same line, but are not clear to me.
On a basic level, there are two things that enable these kinds of things on a Linux (or other POSIX) terminal: ASCII control characters and ANSI escape codes.
For a simple progress bar, it's enough to know how wide the screen is and to have a way to get back to the beginning of the current terminal line. This can be one by reading the environment variable $COLUMNS with getenv and by printing the ASCII control character \r. A very bare-bones and unbeautified example is
#include <iostream>
#include <sstream>
#include <string>
#include <unistd.h>
int main() {
// Default screen width
int width = 80;
// Get screenwidth from environment
char const *envwidth = getenv("COLUMNS");
if(envwidth != nullptr) {
std::istringstream(envwidth) >> width;
}
// save some space for numeric display
width -= 10;
for(int i = 1; i < width; ++i) {
std::cout
<< '\r' // go back to start of line
<< std::string(i, '.') // progress bar
<< std::string(width - i, ' ') // padding
<< "| " << i << '/' << width // numeric display
<< std::flush; // make the progress bar instantly visible
// pretend to work
usleep(100000);
}
}
For more involved terminal "graphics,", there are ANSI escape codes. These allow you to set foreground and background color, move around on the screen at will, and a few other things, by printing special character sequences to stdout. For example,
std::cout << "\x1b[10;20HHello, world." << std::flush;
will print Hello, world. at position 10, 20 on the screen.
There is also the ncurses library that provides more high-level terminal UI functionality (windows, dialogs, that sort of thing). They use ANSI escape codes under the hood, but it's normally nicer to use that than to roll your own UI framework.
I'm making a text based top down game in c++,every time I move my player I need to clear the whole console window with system("CLS") and after that print the whole world again. That process is really slow and inefficient. My question is whether there is any function to clear a certain line in the console window that will not affect the rest of the text? For example, look at the code.
Thanks :)
#include <iostream>
#include<string>
#include "windows.h"
using namespace std;
int main()
{
cout << "hello\n";
cout << "world\n";
//Output:
// hello
// world
//Wanted Output:
//
// world
system("pause");
return 0;
}
I expect text to be printed on the screen and then one line will be cleared without affecting the rest of the text
The win32-API includes a function called SetConsoleCurserPosition: https://learn.microsoft.com/en-us/windows/console/setconsolecursorposition.
I used this function a few years ago.
I have used <windows.h> and <conio.h> on windows for this kind of thing, but on unix the only thing I can find is <ncurses.h>, which uses a lot of C and doesn't support a lot of C++ functions. How can I move the console cursor to (x, y), while also being able to do object-oriented programming?
Edit: I'm trying to make simple games in C++ using the console as a display. I know it's not ideal to do so, but this is for a project that can't use Visual C++ or any other graphics. Think something like snake or minesweeper. I need to be able to cout in different locations, without updating the entire screen in the process. It needs to be compatible with unix systems.
One very simple way is through ANSI escape codes:
#include <iostream>
void moveCursor(std::ostream& os, int col, int row)
{
os << "\033[" << col << ";" << row << "H";
}
int main()
{
moveCursor(std::cout, 1,1);
std::cout << "X (1,1)";
moveCursor(std::cout, 13,8);
std::cout << "X (13,8)" << std::endl;
return 0;
}
The sequence <ESC>[ row , col H (the escape character is ASCII 27 or octal '\033') performs absolut cursor positioning. On most common terminals this should place one "X" in the top-left corner, and the second in column 13, row 8 (counts are 1-based).
Edit: hvd’s comment is of course spot-on: This is very simple, but ncurses is complex for a reason. It is guaranteed to work more reliably and in a much wider variety of settings than a plain escape code. Depending on what you actually want to achieve, I agree with hvd that you should be very careful before picking this simple hack as the solution to your problem.
For anybody else finding this question, this can be accomplished with the kbhit() function in the conio.h library. Just insert !kbhit() where I put SOMETHING and it will loop correctly, I am looking for a way to do this without a library, however.
I'm a beginner trying to create a simple animation in the console. The animation would have the word UP going up the right hand of the console and the word DOWN going down the right hand side. So far I have gotten the animation to complete one iteration of this, but I'm trying to make it so that it repeats and it looks like the texts wraps back to the top or bottom and does it again until the user presses the ENTER key.
My book (I'm self teaching from a textbook) makes it seem that its possible without any specific libraries except for iostream and windows.h but help that includes library functions is welcome too, it is a learning experience after all. Thanks a ton!
A little explanation of the code would be that I set the coordinates of the UP and DOWN starting positions and then move the cursor, delete the previous line it was on with a space and then increment two and put a new word. I would guess that I could use a second while loop to somehow check if the ENTER key has been pressed.
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
HANDLE screen = GetStdHandle(STD_OUTPUT_HANDLE);
COORD upPos = {20,28};
COORD downPos = {50, 0};
char endState;
while ( SOMETHING )
{
COORD upPos = {20,28};
COORD downPos = {50, 0};
while (upPos.Y >=0)
{
SetConsoleCursorPosition(screen,upPos);
cout << "UP" << endl;
upPos.Y++;
SetConsoleCursorPosition(screen,upPos);
cout << " " << endl;
upPos.Y -=2;
SetConsoleCursorPosition(screen,downPos);
cout << "DOWN" << endl;
downPos.Y--;
SetConsoleCursorPosition(screen,downPos);
cout << " " << endl;
downPos.Y+=2;
Sleep(100);
}
}
}
Your best bet is to create a custom "GetAsyncKeyState" function that will use #IFDEF for windows and linux to choose the appropriate GetAsyncKeyState() or equivalent. For ex
if (GetAsyncKeyState(VK_RETURN))
{
exit = true;
}
I've been using Vim a lot lately, and I was wondering how the program manages to change the characters at certain positions in the terminal. For example, when using :rc, it replaces the character under the cursor with c.
I have also seen similar things done with Homebrew, which prints a progress bar to the screen and updates it when necessary.
How is this done in C/C++?
There is no standard way of doing this in C++.
It is done with OS dependent lbiraries, such as curses and similar libraries (ncurses) in the Unix/Linux world. Some of these libraries have been ported on across platforms (example: PDCurses)
For very simple things such as a progress bar or a counter, and as long as you remain on a single line there is the trick of using "\r" (carriage return) in the output, to place the cursor back at the begin of the current line. Example:
for (int i = 0; i < 100; i++) {
cout << "\rProgress: " << setw(3) << i;
this_thread::sleep_for(chrono::milliseconds(100));
}
Certainly, using ncurses or similar library is a good answer. An alternative may be to use ANSI Escape Codes to control the cursor in some terminal emulators (but not Windows command shell). For example, this code prints a line in multiple colors and then moves the cursor to 2,2 (coordinates are 1-based with 1,1 being the upper left corner) and prints the word "red" in the color red.
#include <iostream>
#include <string>
const std::string CSI{"\x1b["};
const std::string BLUE{CSI + "34m"};
const std::string RED{CSI + "31m"};
const std::string RESET{CSI + "0m"};
std::ostream &curpos(int row, int col)
{
return std::cout << CSI << row << ';' << col << 'H';
}
int main()
{
std::cout << "This is " << BLUE << "blue" << RESET << " and white.\n";
curpos(2,2);
std::cout << RED << "red" << RESET << '\n';
}
As mentioned that's not a matter of any C/C++ standard operations provided with stdout or cout (besides writing the necessary control characters to the screen).
Controlling the screen cursor of an ASCII terminal totally depends on implementation of the particular terminal program used, and besides a very narrow set of control characters, there's no standard established.
There are libraries like ncurses for a broader variety of linux terminal implementations, or PDcurses for a windows CMD shell.
I'm not sure to understand you completely but with creating an array of 100 elements of type char you can modify any position of the array and loop it with a std:cout to mostrate it on the console.
Perhaps could be better define the array of 50 chars to resuce the size of the printed result.
For example, if you have to print a progessbar in the 1% process, you should print:
Char progressbar[100] = {'X','','','','','','','','',........}