Console writing, delete characters - c++

My question concerns deleting already written chars in the console. Is there a way to do it?
Lets say i write 10 spaces to the console. Can i delete some to make space for other chars without the output exeeding 10 chars? I use a special libary given, with functions for writing in the console etc.

Use '\b'. It erases one character, and the cursor moves back:
std::cout << "nawaz"; //screen shows : nawaz
std::cout << '\b'; //'z' is erased, now screen shows : nawa

do {
cout<<"\b"<<num--;
}
while ( num >0 );

Depends on the type of terminal you're using, you could use the escape codes to control it.
For Windows, there are also API functions, if I remember correctly.

Related

Why does getchar work like a buffer instead of working as expected in real-time

This is my first question on stackoverflow. Pardon me if I haven't searched properly but I do not seem to find an explanation for this. Was just attempting an example from Bjourne Stroustroup's papers. Added my bits to see the array get re-sized as I type the text.
But it doesn't seem to work that way! getchar() simply waits till I am done with entering all the characters and then it will execute the loop. As per the logic, it doesn't actually go into the loop, get a character, perform its actions and then iterate. I am wondering if this is implementation specific, or intended to be like this?
I am on Ubuntu 14.04 LTS using Codeblocks with gcc 4.8.2. The source was in cpp files if that matters.
while(true)
{
int c = getchar();
if(c=='\n' || c==EOF)
{
text[i] = 0;
break;
}
text[i] = c;
if(i == maxsize-1)
{
maxsize = maxsize+maxsize;
text = (char*)realloc(text,maxsize);
if(text == 0) exit(1);
cout << "\n Increasing array size to " << maxsize << endl;
}
i++;
}
The output is as follows:
Array Size is now: 10
Please enter some text: this is some sample text. I would have liked to see the memory being realloced right here, but apparently that's not how it works!
Increasing array size to 20
Increasing array size to 40
Increasing array size to 80
Increasing array size to 160
You have entered: this is some sample text. I would have liked to see the memory being realloced right here, but apparently that's not how it works!
Array Size is now: 160
This has nothing to do with getchar directly. The "problem" is the underlying terminal, which will buffer your Input. The Input is sent to the program after you press enter. In Linux (dunno if there is a way in Windows) you can workaround this by calling
/bin/stty raw
in terminal or by calling
system ("/bin/stty raw");
in your program. This will cause getchar to immediately return the input character to you.
Dont forget to reset the tty behaviour by calling
/bin/stty cooked
when done!
Here is an example (for Linux):
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main() {
system ("/bin/stty raw");
char c = getchar();
system ("/bin/stty cooked");
return 0;
}
Also have a look at this SO Post: How to avoid press enter with any getchar()
Also, as suggested in the comments, have a look here: http://linux.die.net/man/3/termios especially on the command tcsetattr, which should work cross-platform.
Actually, tcsetattr does not apply to Windows (which is what is commonly referred to in this site as "cross-platform"). However, the question is tagged for Linux, so "cross-platform" is a moot point.
By default the standard input, output and error streams are set to
line-buffered (input)
block-buffered (output)
line-buffered (error)
You can change that using setbuf, but of course will not solve the problem (the answer calls for single-character input). POSIX terminal I/O (termios) lets you change via a system call any of the flags shown using stty. As a rule, you might call stty directly from a script, rarely from a C program.
Reading a single character is a frequently asked question, e.g.,
How can I read single characters from the terminal? (unix-faq)
How can I read a single character from the keyboard without waiting for the RETURN key? How can I stop characters from being echoed on the screen as they're typed? (comp.lang.c FAQ)
You could also use ncurses: the filter function is useful for programs that process a command-line (rather than a full-screen application). There is a sample program in ncurses-examples (filter.c) which does this.

How do I rewrite a line of text in a console project? c++

I'm working on a c++ console project and i would like to show a percentage without making a new line each time (so that the window doesn't get clogged with thousands of lines).
Is there a way of removing the last line that was printed or something to say that the next time that i output a line it should replace the current line?
You can use a \r (carriage return) to return the cursor to the beginning of the line:
This works on windows and Linux.
From: Erase the current printed console line
You could alternatively use a series of backspaces.
string str="Hello!";
cout << str;
cout << string(str.length(),'\b');
cout << "Hello again!";
From: http://www.cplusplus.com/forum/unices/25744/
Maybe mark as duplicate? I am really not sure how.
A simple example that I tested on Linux would be:
std::cout << "Some text to display..." << "\t\r" << std::flush;
Here the \t adds a tabulation to handle slightly varying string lengths and \r sends the cursor back at the start of the line (as mentioned in other answers).
std::flush is required to guarantee that the line is displayed without jumping to the next line.
This is very platform-dependent and terminal-dependent. But, you may want to look at ncurses for a start: http://linux.die.net/man/3/ncurses
For Windows: How can I overwrite the same portion of the console in a Windows native C++ console app, without using a 3rd Party library?
For Linux: https://unix.stackexchange.com/questions/43075/how-to-change-the-contents-of-a-line-on-the-terminal-as-opposed-to-writing-a-new

How do I set cursor position to beginning of line in C++?

So I'm trying to make part of a code where it writes something, then overwrites it. Like this:
10 seconds have passed
11 seconds have passed
12 seconds have passed
without using a new line to print it. So I don't want to use something like this:
std::cout<<"10 seconds have passed\n"
std::cout<<"11 seconds have passed\n"
How do I do this? I'm running Kubuntu Linux
That's what the carriage return character is for: \r. It is named after the mechanism of typewriters that returns the paper carriage to the right so that the typist can continue typing from the beginning of a line. Try this:
std::cout << "10 seconds have passed";
std::cout << "\r11";
Of course, with no delay between the two (except perhaps waiting on I/O), you're unlikely to see the change, but you will at least see the output as 11 seconds have passed with 10 nowhere to be seen.
How to display the carriage return is entirely up to whatever you're outputting to, but this is its intention. For more complex cross-platform terminal output, take a look at ncurses.
#include <conio.h>
#include <consoleapi.h>
void gotoxy(short x, short y)
{
HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
COORD position = { x, y };
SetConsoleCursorPosition(hStdout, position);
}
If you need better moving in console.
(i dont know why it not showing corectly #include conio.h
Besides \r (that takes you back to the beginning of the line), you can also use the \b character to get back of one character. If you have to do more complicated stuff, you'll have to use the VT100 escape codes or some library (like ncurses).
Try
cout<<"\roverride"
With no linebreak at the end. The \r means carage return which means to jump to the beginning of a line.
The carriage return '\r' is responsible for moving back to beginning of line.
Not that you have to override all characters that have been written because they are not deleted automatically on display.
And don't forget to call the flush of std::cout because otherwise on unix machines you may not see any results until its flushed.

C++ changing output on console

What is the easiest way to display changing numbers in the console? I have a normal command line program in C++ which uses cout, but I'd like to display a percentage number representing the progress which counts up to 100 without printing a new line. How is that done? (If it matters: I'm on Windows 7)
When I’ve needed that I have just output a carriage return character, in C++ \r.
Remember to flush the output each time, e.g.
cout << "\r" << x << "% completed. " << flush;
The spaces at the end to clear previous output on the line in case of Microsoft-like fluctuating progress.
Use the backspace character.
cout << "10%";
// ...
cout << "\b\b\b20%";
I normally place a carriage return after the progress information. That way, any other output will appear normal (as long as it has enough characters in the line to completely overwrite the progress info).
cerr<<percentage<<"% \r";
By the way, I prefer to use cerr instead of cout for this kind of status/diagnostic information so that cout can be reserved for real content. This way you can redirect the normal program output to a file and still see the progress in the console. Also, with cerr, you don't have to use "flush".

Superscript in C++ console output

I'd like to have my program output "cm2" (cm squared).
How do make a superscript 2?
As Zan said, it depends what character encoding your standard output supports. If it supports Unicode , you can use the encoding for ²(U+00B2). If it supports the same Unicode encoding for source files and standard output, you can just embed it in the file. For example, my GNU/Linux system uses UTF-8 for both, so this works fine:
#include <iostream>
int main()
{
std::cout << "cm²" << std::endl;
}
This is not something C++ can do on its own.
You would need to use a specific feature of your console system.
I am not aware of any consoles or terminals that implement super-script. I might be wrong though.
I was trying to accomplish this task for the purpose of making a quadratic equation solver. Writing ax² inside a cout << by holding ALT while typing 253 displayed properly in the source code only, BUT NOT in the console. When running the program, it appeared as a light colored rectangle instead of a superscript 2.
A simple solution to this seems to be casting the integer 253 as a char, like this... (char)253.
Because our professor discourages us from using 'magic numbers', I declared it as a constant variable... const int superScriptTwo = 253; //ascii value of super script two.
Then, where I wanted the superscript 2 to appear in the console, I cast my variable as a char like this...
cout << "f(x) = ax" << (char)superScriptTwo << " + bx + c"; and it displayed perfectly.
Perhaps it's even easier just to create it as a char to begin with, and not worry about casting it. This code will also print a super script 2 to the console when compiled and run in VS2013 on my Lenovo running Windows 7...
char ssTwo = 253;
cout << ssTwo << endl;
I hope someone will find this useful. This is my first post, ever, so I do apologize in advance if I accidentally violated any Stack Overflow protocols for answering a question posted 5+ years ago. Any such occurrence was not intentional.
Yes, I agree with Zan.
Basic C++ does not have any inbuilt functionality to print superscripts or subscripts. You need to use any additional UI library.
std::cout << cm\x00B2;
writes cm^2.
For super scripting or sub scripting you need to use ascii value of the letter or number.
Eg: Super scripting 2 for x² we need to get the ascii value of super script of 2 (search in google for that) ie - 253. For typing ascii character you have to do alt + 253 here, you can write a any number, but its 253 in this case.
Eg:-cout<<"x²";
So, now it should display x² on the black screen.
Why don't you try ASCII?
Declare a character and give it an ASCII value of 253 and then print the character.
So your code should go like this;
char ch = 253;
cout<<"cm"<<ch;
This will definitely print cm2.