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.
精彩评论