Changing the colour of debug output - c++

I sometimes use the class DOut (listed below) for debugging
#include<fstream>
#include<iostream>
#include<sstream>
#define WIN32_LEAN_AND_MEAN
#include<Windows.h>
#ifdef UNICODE
#define tostream wostream
#define tostringstream wostringstream
#define _T(x) L##x
#else
#define tostream ostream
#define tostringstream ostringstream
#define _T(x) x
#endif
class DOut : public std::tostringstream
{
public:
//http://stackoverflow.com/questions/2212776/overload-handling-of-stdendl
DOut& operator << (std::tostream&(*f)(std::tostream&))
{
if (f == std::endl)
{
*this << _T("\n");
OutputDebugString(str().c_str());
str(_T(""));
}
else
{
*this << f;
}
return *this;
}
//https://hbfs.wordpress.com/2010/12/21/c-logging/
template <typename TT>
inline DOut & operator << (const TT& t)
{
(*(std::tostringstream*) this) << t;
return *this;
}
};
int main()
{
DOut dout;
int x = 20;
dout << "x = " << x << std::endl;
dout << "x * x = " << x * x << std::endl;
dout << "hexq=" << x*x << "=" << std::hex << x * x << std::endl;
}
It works quite well except it gets interleaved with all the VS output information. For example
'dout.exe': Loaded 'U:\GCS\test\dout\Debug\dout.exe', Symbols loaded.
'dout.exe': Loaded 'C:\WINDOWS\system32\ntdll.dll'
'dout.exe': Loaded 'C:\WINDOWS\system32\kernel32.dll'
'dout.exe': Loaded 'C:\WINDOWS\WinSxS\x86_Microsoft.VC90.DebugCRT_1fc8b3b9a1e18e3b_9.0.30729.1_x-ww_f863c71f\msvcp90d.dll'
'dout.exe': Loaded 'C:\WINDOWS\WinSxS\x86_Microsoft.VC90.DebugCRT_1fc8b3b9a1e18e3b_9.0.30729.1_x-ww_f863c71f\msvcr90d.dll'
x = 20
x * x = 400
hexq=400=190
The program '[3108] dout.exe: Native' has exited with code 0 (0x0).
The above is not strictly accurate as I don't know how to get stackoverflow to display monochrome text. All the text is just in a single colour. I could always output it to a file but this is convenient as I don't always have a console window and I don't have to worry about chdirs which change where the output file is written to.
I just wondering whether it is possible to output my debug information in a different colour. I've tried ANSI escape sequences but they don't work.

If I understand you right, you can do such things with help of extensions: VSColorOutput or VSCommands for Visual Studio
They can change appearance in the output window. You can use out of the box behavior or add some special characters when outputting with DOut class and create own rule how to color it.
VSColorOutput hooks into the the classifier chain of Visual Studio. This allows VSColorOutput to monitor every line sent to the output window. A list of classifiers, consisting of regular expressions and classifications is checked. The first matching expression determines the classification the line of text. If no patterns match, then line is classified as a common build text.

Actually, the answer is easier than I thought. Just right click in the output window and select Program Output. It just shows you the program output without all the other bits. No need for colours.
Also, it is available from VS2005 up to the current version without any need for installing different Visual Studio extensions for the different versions of VS.

Related

Printing Chinese Characters in C++

I've been trying to print Chinese Characters in C++. I've already searched around in the Internet, some said that you have to use wcout, others have suggested other methods. I've also stumbled on this post, where someone uses a piece of code:
#include <iostream>
int main()
{
char x[] = "中";
char y[] = u8"中";
wchar_t z = L'中';
char16_t b = u'\u4e2d';
char32_t a = U'\U00004e2d';
std::cout << x << '\n';
std::cout << y << '\n';
std::wcout << z << '\n';
std::cout << a << '\n';
std::cout << b << '\n';
}
which, on an internet site that shows the output of C++ code, prints:
中
中
-
20013
20013
However, for me it just prints
õ©¡
õ©¡
20013
20013
I'm using JetBrains CLion, with encoding set to UTF-8. However, I've also tried Visual Studio and QT Creator, I get the same result. I hope someone can help me out.
If you're using OSX Terminal maybe you can check the Encoding.
Terminal -> Preferences -> Encodings Tab
Then check if Traditional Chinese is checked or Unicode (UTF-8).
For Windows, you can try this, to change to UTF-8 encoding.
Go to Start then Run "regedit" -> Navigate to [HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\Autorun] -> modify value to "chcp 65001"
Hope this helps.

I want to make my console more colorful. How can I make the user input (obtained through getline) colorful while they type?

I was just wondering if it is possible to color text while the user is typing it into the console.
I am using a color library for cout'ed text, but I wanted to know if it's possible to color the text while the user is inputting his/her string?
You can use Windows console APIs to do so:
HANDLE console_output = ::GetStdHandle(STD_OUTPUT_HANDLE);
::SetConsoleTextAttribute(console_output, FOREGROUND_GREEN);
std::string buffer;
std::getline(std::cin, buffer);
std::cout << buffer << std::endl;
::CloseHandle(console_output);
Input text will be green in color. Also, don't forget to include windows.h
On linux/macOS just do as following :
#include <iostream>
int main()
{
std::string foo;
std::cout << "Type your text here : \x1B[31m";
std::cin >> foo;
std::cout << "\x1B[0m" << std::endl;
std::cout << "Your input : " << foo << std::endl;
return (0);
}
A litte explanation :
when you type one of the followings specific strings :
"\x1B[31m" (red)
"\x1B[32m" (green)
"\x1B[33m" (yellow)
"\x1B[34m" (blue)
"\x1B[35m" (magenta)
"\x1B[36m" (cyan)
"\x1B[0m" (reset)
it will use termcap (stand for terminal capabilities) and change the color of all the output written after.
Don't forget to reset after using these termcap otherwise your terminal will stuck to the chosen color until you reset it.
PS : Don't know if it works for windows.

In C/C++, how do you edit a certain 'coordinate' in stdout?

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','','','','','','','','',........}

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/

Strange newline issue after DLL call C++ Windows

The Problem
I'm developing an 32 bit unmanaged application in C++ on Windows using Visual Studio 2010. Forgive my lack of Windows knowledge as I usually develop on *nix.
Initially, in my program my calls to std::cout's stream insertion operator work fine. For example, the following statement outputs as expected:
std::cout << "hello" << std::endl;
However, the following code does not work:
std::cout << "\thello" << std::endl;
...call to DLL from Japanese company who won't respond to support requests...
std::cout << "\thello" << std::endl;
The above code prints:
hello
(inverted diamond symbol)hello(eighth note music symbol)(inverted o symbol)
Once I have called this DLL for the first time my output to std::cout is forever messed up. The symbols that are printed are not found in an ASCII table. The inverted o symbol is a single unicode char that looks like the letter 'o' but the black part of the o is white, and the white part is black(inverted colors). The music symbol is the unicode 8th note character.
Any ideas on why this is happening and how to fix it? It seems that this DLL is messing up how control characters (chars starting with \) are outputted.
What I have tried so far
I thought this might be a locale issue since the DLL is from a Japanese company. However, after the DLL call the locale is still "C" just as it was before the call. I use the following to query the locale:
printf ("Locale is: %s\n", setlocale(LC_ALL,NULL) );
I also thought this might be some kind of bizarre memory corruption but it seems that the \r\n gets replaced by (music symbol)(inverted o) whereas \t gets replaced by an inverted diamond symbol. There seems to be a regular "replace A by B" pattern for all the control chars, which would not indicate memory corruption.
Lastly, I also tried this:
std::cout << "blah" << '\r' << '\n';
and I see the same garbage characters created by:
std::cout << "blah" << std::endl;
Thanks in advance for any help and insight.
See whether this fixes it:
#include <iostream>
#include <locale>
int main()
{
std::cout << "\thello" << std::endl;
// ...call to DLL from Japanese company who won't respond to support requests...
locale mylocale(""); // or "C" // Construct locale object with the user's default preferences
std::cout.imbue( mylocale ); // Imbue that locale
std::cout << "\thello" << std::endl;
return 0;
}
Consult the documentation for that library whether
the change of locale is by design
it can be configured otherwise
You could perhaps associate another stream with cout
std::ostream cout2;
cout2.rdbuf(std::cout.rdbuf());
And use it. I'm sure that won't be thread safe. Flushing might be 'awkward' - but it should work