Console output in cmd.exe, and powershell.exe through C++ - c++

I know a simple way for correct displaying of localized chars on Cmd.exe. But how can I do same for Powershell.exe?
#include<iostream>
#include<windows.h>
using namespace std;
int main()
{
SetConsoleCP(GetACP());
SetConsoleOutputCP(GetACP());
// valid output in cmd.exe,
// but invalid output in powershell.exe
cout << "Привет мир (1)!" << endl;
// invalid output in both variants: cmd.exe,
// and powershell.exe
wcout << L"Привет мир (2)!" << endl;
return 0;
}

What is the output? Is your font supporting those glyphs?
perhaps the following link may be useful (about cmd.exe):
http://www.watchingthenet.com/how-to-add-and-change-fonts-in-windows-command-prompt.html
You could also try to redirect output from powershell to a file and check that. If the file is correct, you have a console-font not supporting your characters.
there is also a blog from ms, showing how to customize the font (about ps)
http://blogs.msdn.com/b/powershell/archive/2006/10/16/windows-powershell-font-customization.aspx

I think that's there's a shortcut to enable proper wcout handling in Windows. Try to add that as a first line to your main:
_setmode(_fileno(stdout), _O_U16TEXT);
After that wcout << L"Привет мир (2)!" << endl; will work like a charm independently of current locale and single-byte encoding chosen by user (as it should).

Related

Is there a proper way to receive input from console in UTF-8 encoding?

When getting input from std::cin in windows, the input is apparently always in the encoding windows-1252 (the default for the host machine in my case) despite all the configurations made, that apparently only affect to the output. Is there a proper way to capture input in windows in UTF-8 encoding?
For instance, let's check out this program:
#include <iostream>
int main(int argc, char* argv[])
{
std::cin.imbue(locale("es_ES.UTF-8"));
std::cout.imbue(locale("es_ES.UTF-8"));
std::cout << "ñeñeñe> ";
std::string in;
std::getline( std::cin, in );
std::cout << in;
}
I've compiled it using visual studio 2022 in a windows machine with spanish locale. The source code is in UTF-8. When executing the resulting program (windows powershell session, after executing chcp 65001 to set the default encoding to UTF-8), I see the following:
PS C:\> .\test_program.exe
ñeñeñe> ñeñeñe
e e e
The first "ñeñeñe" is correct: it display correctly the "ñ" caracter to the output console. So far, so good. The user input is echoed back to the console correctly: another good point. But! when it turns to send back the encoded string to the ouput, the "ñ" caracter is substituted by an empty space.
When debugging this program, I see that the variable "in" have captured the input in an encoding that it is not utf-8: for the "ñ" it use only one character, whereas in utf-8 that caracter must consume two. The conclusion is that the input is not affect for the chcp command. Is something I doing wrong?
UPDATE
Somebody have asked me to see what happens when changing to wcout/wcin:
std::wcout << u"ñeñeñe> ";
std::wstring in;
std::getline(std::wcin, in);
std::wcout << in;
Behaviour:
PS C:\> .\test.exe
0,000,7FF,6D1,B76,E30ñeñeñe
e e e
Other try (setting the string as L"ñeñeñe"):
ñeñeñe> ñeñeñe
e e e
Leaving it as is:
std::wcout << "ñeñeñe> ";
Result is:
eee>
This is the closest to the solution I've found so far:
int main(int argc, char* argv[])
{
_setmode(_fileno(stdout), _O_WTEXT);
_setmode(_fileno(stdin), _O_WTEXT);
std::wcout << L"ñeñeñe";
std::wstring in;
std::getline(std::wcin, in);
std::wcout << in;
return 0;
}
The solution depicted here went in the right direction. Problem: both stdin and stdout should be in the same configuration, because the echo of the console rewrites the input. The problem is the writing of the string with \uXXXX codes.... I am guessing how to overcome that or using #define's to overcome and clarify the text literals

Get rid of space when printing a new line using standard output in c++ and ncurses

Hello I'd like to know how to get rid of the space created
when printing a new line in c++ using ncurses library.
#include <iostream>
#include <ncurses.h>
using namespace std;
int main(){
initscr();
noecho();
cout << "Hello" << endl;
cout << "World" << endl;
endwin();
return 0;
}
I have this output
Hello
----World
(The dashes are the space I mean)
Offhand, I'd expect this output:
Hello
World
since curses puts the screen into raw mode, suppressing the cooked-mode feature that converts output line-feeds into carriage-return/line-feed. If you really want to print
Hello
World
you should use curses calls (which also happen to work with curses output buffering):
addstr("Hello\n");
addstr("World\n");
Besides the misformatted output, mixing cout with curses can cause your output to be sent in a different order than the curses calls. That's what I meant by buffering.

How to disable cout output in the runtime?

I often use cout for debugging purpose in many different places in my code, and then I get frustrated and comment all of them manually.
Is there a way to suppress cout output in the runtime?
And more importantly, let's say I want to suppress all cout outputs, but I still want to see 1 specific output (let's say the final output of the program) in the terminal.
Is it possible to use an ""other way"" of printing to the terminal for showing the program output, and then when suppressing cout still see things that are printed using this ""other way""?
Sure, you can (example here):
int main() {
std::cout << "First message" << std::endl;
std::cout.setstate(std::ios_base::failbit);
std::cout << "Second message" << std::endl;
std::cout.clear();
std::cout << "Last message" << std::endl;
return 0;
}
Outputs:
First message
Last message
This is because putting the stream in fail state will make it silently discard any output, until the failbit is cleared.
To supress output, you can disconnect the underlying buffer from cout.
#include <iostream>
using namespace std;
int main(){
// get underlying buffer
streambuf* orig_buf = cout.rdbuf();
// set null
cout.rdbuf(NULL);
cout << "this will not be displayed." << endl;
// restore buffer
cout.rdbuf(orig_buf);
cout << "this will be dispalyed." << endl;
return 0;
}
Don't use cout for debugging purposes, but define a different object (or function, or macro) that calls through to it, then you can disable that function or macro in one single place.
You can user cerr - standard output stream for errors for your debug purposes.
Also, there is clog - standard output stream for logging.
Typically, they both behave like a cout.
Example:
cerr << 74 << endl;
Details: http://www.cplusplus.com/reference/iostream/cerr/
http://www.cplusplus.com/reference/iostream/clog/
If you include files which involve cout you may want to write the code at the start (outside of main), which can be done like this:
struct Clearer {
Clearer() { std::cout.setstate(std::ios::failbit); }
} output_clearer;
It seems you print debug messages. You could use TRACE within Visual C++/MFC or you just might want to create a Debug() function which takes care of it. You can implement it to turn on only if a distinct flag is set. A lot of programs use a command line parameter called verbose or -v for instance, to control the behavior of their log and debug messages.

Windows console does not display square root sign

For a console application, I need to display the symbol: √
When I try to simply output it using:
std::cout << '√' << std::endl; or
std::wcout << '√' << std::endl;,
it outputs the number 14846106 instead.
I've tried searching for an answer and have found several recommendations of the following:
std::cout << "\xFB" << std::endl; and
std::cout << (unsigned char)251 << std::endl;
which both display a superscript 1.
This is using the Windows console with Lucida font. I've tried this with various character pages and always get the same superscript 1. When I try to find its value through getchar() or cin, the symbol is converted into the capital letter V. I am, however, sure that it can display this character simply by pasting it in. Is there an easy way of displaying Unicode characters?
Actually "\xFB" or (unsigned char)251 are the same and do correspond to the root symbol √... but not in the Lucida font and other typefaces ASCII table , where it is an ¹ (superscript 1).
Switching to Unicode with the STL is a possibility, but I doubt it will run on Windows...
#include <iostream>
#include <locale.h>
int main() {
std::locale::global(std::locale("en_US.UTF8"));
std::wcout.imbue(std::locale());
wchar_t root = L'√';
std::wcout << root << std::endl;
return 0;
}
Since this will not satisfy you, here a portable Unicode library: http://site.icu-project.org/

Output unicode symbol π and ≈ in c++ win32 console application

I am fairly new to programming, but it seems like the π(pi) symbol is not in the standard set of outputs that ASCII handles.
I am wondering if there is a way to get the console to output the π symbol, so as to express exact answers regarding certain mathematical formulas.
I'm not really sure about any other methods (such as those that use the STL) but you can do this with Win32 using WriteConsoleW:
HANDLE hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE);
LPCWSTR lpPiString = L"\u03C0";
DWORD dwNumberOfCharsWritten;
WriteConsoleW(hConsoleOutput, lpPiString, 1, &dwNumberOfCharsWritten, NULL);
The Microsoft CRT is not very Unicode-savvy, so it may be necessary to bypass it and use WriteConsole() directly. I'm assuming you already compile for Unicode, else you need to explicitly use WriteConsoleW()
I'm in the learning phase of this, so correct me if I get something wrong.
It seems like this is a three step process:
Use wide versions of cout, cin, string and so on. So: wcout, wcin, wstring
Before using a stream set it to an Unicode-friendly mode.
Configure the targeted console to use an Unicode-capable font.
You should now be able to rock those funky åäös.
Example:
#include <iostream>
#include <string>
#include <io.h>
// We only need one mode definition in this example, but it and several other
// reside in the header file fcntl.h.
#define _O_WTEXT 0x10000 /* file mode is UTF16 (translated) */
// Possibly useful if we want UTF-8
//#define _O_U8TEXT 0x40000 /* file mode is UTF8 no BOM (translated) */
void main(void)
{
// To be able to write UFT-16 to stdout.
_setmode(_fileno(stdout), _O_WTEXT);
// To be able to read UTF-16 from stdin.
_setmode(_fileno(stdin), _O_WTEXT);
wchar_t* hallå = L"Hallå, värld!";
std::wcout << hallå << std::endl;
// It's all Greek to me. Go UU!
std::wstring etabetapi = L"η β π";
std::wcout << etabetapi << std::endl;
std::wstring myInput;
std::wcin >> myInput;
std:: wcout << myInput << L" has " << myInput.length() << L" characters." << std::endl;
// This character won't show using Consolas or Lucida Console
std::wcout << L"♔" << std::endl;
}