Superscript in C++ console output - c++

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.

Related

C++ Console Output Manipulation [duplicate]

This question already has answers here:
C++ Update console output
(4 answers)
Closed 5 years ago.
I'm developing some application in which I want to manipulate some data comming from the embedded system. So, what do I want to do is that I want to display the values which are comming on the same position where they were before, leaving the static text on the same place and not using new line. Being more specific, I want to output my data in form of a table, and in this table on the same positions I want to update that data. There is some analogy in Linux, when in the terminal there is some update of the value(let's say some progress) while the static text remains and only the value is changing.
So, the output should look like this:
Some_data: 0xFFFF
Some_data2: 0xA1B3
Some_data3: 0x1201
So in this case, "Some_data" remains unchanged on the same place, and only the data itself is updated.
Are there maybe some libraries for doing that? What about Windows Console Functions? Also, it would be very nice if it could be made in such a way, in which the console would not flick, like when you clear the console and print something back. Any hints or suggestions? Thanks very much in advance guys!
P.S. There is no need to write the code, I just need some hints or suggestions, with very short examples if possible(but not required).
On a *nix system you have two options.
1) If you want to manipulate the entire console in table form like you ask, then ncurses is the best option. The complete reference can be found here.
As you can see, that package is quite heavyweight and can often be overkill for simple projects, so I often use . ..
2) If you can contain your changing information on a single line, use the backspace escape char \b and then rewrite the information repeatedly to that line
For example, try this . . .
#include <iostream>
#include <chrono>
#include <thread>
using namespace std;
void writeStuff(int d)
{
cout << string(100,'\b') << flush;
cout << "Thing = " << d;
}
int main()
{
cout << "AMAZING GIZMO" << "\n============" << endl;
while(1) {
writeStuff(rand());
this_thread::sleep_for(chrono::milliseconds(250));
}
}
For a real world example, the sox audio console playback command uses this technique to good effect by displaying a bar chart made of console characters to represent the audio playback level in real time.
Of course, you can get more creative with the method shown above if your console supports ANSI escape sequences.

How to print degree symbol on the window using qt5(QtQuick 2.1) and above

When I was using up to qt4.8(qt quick 1.1) for gui then I am successfully able to print degree with \260 but when things got upgraded to qt5 and above then this stopped working. I searched on the net and found many relevant link such as (http://www.fileformat.info/info/unicode/char/00b0/index.htm) I tried but no help. Do I need to include some library for usinf UTF format or problem is sth else. Please some one help. What to do?
#Revised,
Here it is described what is being done.
First I am storing the printable statement in string text.
As in cpp function:-
sprintf(text, "%02d\260 %03d\260 ",latD, longD);
QString positionText(text.c_str());
return positionText;
And then using positionText in qml file to display on the window.
So, someone please answer what do I need to do to have degree in display?
Thanks.
Problem is simple you used \260 most probably inside Ansii C-string (const char []). In such cases Qt has use some codec to convert this to Unicode characters. For some reason when you change Qt version default codec was changed and this is why it stopped working.
Anyway your approach is wrong. You shouldn't use C-string which are codec depended (usually this leads to this kind of problems). You can define QChar const as QChar(0260) or best approach is to use tr and provide translation.
It would be best if you give representative example with string with degree character, then someone will provide you best solution.
Edit:
I would change your code like this:
const QChar degreeChar(0260); // octal value
return QString("%1%3 %2%3").arg(latD, 2, 10, '0').arg(longD, 3, 10, '0').arg(degreeChar);
or add translation which will handle this line:
return tr("%1degree %2degree").arg(latD, 2, 10, '0').arg(longD, 3, 10, '0');
Note that this translation for this line only have to be added always no mater what is current locale.
Try
return QString::fromLatin1(text);
or, if that doesn't work, another static QString::fromXXX method.
QT5 changed Qt's default codec from Latin-1 to UTF-8, as described here:
https://www.macieira.org/blog/2012/05/source-code-must-be-utf-8-and-qstring-wants-it/
Latin-1 and Unicode both use 176 (0xB0 or 0260) as the degree symbol, so your usage of it coincidentally worked, since it was interpreted as Latin-1 and converted to the same value in Unicode.
That first line could be changed to:
sprintf(text, "%02d\302\260 %03d\302\260 ",latD, longD);
As mentioned before, going directly to a QString is indeed better, but if you had to go through a std::string, you could simply substitute the UTF-8 encoding of Unicode 176, in which the lower 6 bits 110000 would have a 10 prepended, and the upper 2 bits 10, would have 110000 prepended in the first byte. This becomes: \302\260.
To easily print angles with degree symbols in console, try this:
#include <QDebug>
double v = 7.0589;
qDebug().noquote() << "value=" << v << QString(248);
Console output:
value= 7.0589 °
This works out-of-the-box under Windows.

Basic terminal output using C++ - Questions

Well, the question may sound a bit too vague but here's 2 things I need to do and I'd definitely need some input on this :
Output something (e.g. using cout) with color (note: My TERM environment variable is set to xterm-color if that makes any difference; also, is there any uniform way to output colored text that's compatible with both pure mac and *nix terminals in general, so that the code is portable)
Output something at the same position on the terminal screen. OK, this may sound confusing too. Let's take a terminal app which simply outputs a progress percentage. It normally won't start a new line for that. The new value is shown at the very same spot. How is this doable? (Being a once Borland Pascal guy from the good old DOS days, the only thing I could think of is something to do with accessing video memory directly... or not?)
So... any ideas?
You probably want to use ncurses library. And ANSI escape codes can also be used for coloring.
1)
You can try Color cout , but that is not protable. I tried (ANSI escape codes) something like
cout << "\033[1;31mbold red text\033[0m\n";
cout << "\33[0;31m" << "Enter Your String here" << "\33[0m" << std::endl ;
You can also look at
How do I output coloured text to a Linux terminal?
2)
Are you looking for something like watch or top like app which are showing output at the same spot.

Console writing, delete characters

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.

How to print subscripts/superscripts on a CLI?

I'm writing a piece of code which deals with math variables and indices, and I'd need to print subscripts and superscripts on a CLI, is there a (possibly cross-platform) way to do that? I'm working in vanilla C++.
Note: I'd like this to be cross-platform, but since from the first answers this doesn't seem to be possible I'm working under MacOS and Ubuntu Linux (so bash).
Thank you
Since most CLIs are really only terminals (pretty dumb ones mostly but sometimes with color), the only cross-platform way I've ever done this is by allocating muliple physical lines per virtual line, such as:
2
f(x) = x + log x
2
It's not ideal but it's probably the best you're going to get without a GUI.
Following you extra information as to what platforms you're mainly interested in:
With Ubuntu at least, gnome-terminal runs in UTF-8 mode by default so the following code shows how to generate the superscripts and subscripts:
#include <stdio.h>
static char *super[] = {"\xe2\x81\xb0", "\xc2\xb9", "\xc2\xb2",
"\xc2\xb3", "\xe2\x81\xb4", "\xe2\x81\xb5", "\xe2\x81\xb6",
"\xe2\x81\xb7", "\xe2\x81\xb8", "\xe2\x81\xb9"};
static char *sub[] = {"\xe2\x82\x80", "\xe2\x82\x81", "\xe2\x82\x82",
"\xe2\x82\x83", "\xe2\x82\x84", "\xe2\x82\x85", "\xe2\x82\x86",
"\xe2\x82\x87", "\xe2\x82\x88", "\xe2\x82\x89"};
int main(void) {
int i;
printf ("f(x) = x%s + log%sx\n",super[2],sub[2]);
for (i = 0; i < 10; i++) {
printf ("x%s x%s ", super[i], sub[i]);
}
printf ("y%s%s%s z%s%s\n", super[9], super[9], super[9], sub[7], sub[5]);
return 0;
}
The super and sub char* arrays are the UTF-8 encodings for the Unicode code points for numeric superscripts and subscripts (see here). The given program will output my formula from above (on one line instead of three), then another test line for all the choices and a y-super-999 and z-sub-75 so you can see what they look like.
MacOS doesn't appear to use gnome-terminal as a terminal program but references here and here seem to indicate the standard terminal understands UTF-8 (or you could download and install gnome-terminal as a last resort).
I'd need to print subscripts and superscripts on a CLI, is there a cross-platform way to do that?
Only if you have a Unicode-capable terminal, which is far from guaranteed. Unicode defines a limited number of sub- and superscript ‘compatibility characters’, you certainly can't use it on any old letter:
₀₁₂₃₄₅₆₇₈₉₊₋₌₍₎ₐₑₒₓ
⁰¹²³⁴⁵⁶⁷⁸⁹⁺⁻⁼⁽⁾ⁿⁱ
Even then you're reliant on there being a glyph for it in the console font, which is also far from guaranteed. Superscript 2 and 3 are likely to exist as they're present in ISO-8859-1; the others may well not work.