Simo Pelle
Simo Pelle

Reputation: 169

Cout unsigned char

I'm using Visual Studio 2019: why does this command do nothing?

std::cout << unsigned char(133);

It literally gets skipped by my compiler (I verified it using step-by-step debug): I expected a print of à. Every output before the next command is ignored, but not the previous ones. (std::cout << "12" << unsigned char(133) << "34"; prints "12")

I've also tried to change it to these:

std::cout << unsigned char(133) << std::flush;
std::cout << (unsigned char)(133);
std::cout << char(-123);

but the result is the same.

I remember that it worked before, and some of my programs that use this command have misteriously stopped working... In a blank new project same result!

I thought that it my new custom keyboard layout could be the cause, but disabling it does not change so much.

On other online compilers it works properly, so may it be a bug of Visual Studio 2019?

Upvotes: 1

Views: 710

Answers (2)

Bartek Banachewicz
Bartek Banachewicz

Reputation: 39380

The "sane" answer is: don't rely on extended-ASCII characters. Unicode is widespread enough to make this the preferred approach:

#include <iostream>
int main() {
    std::cout << u8"\u00e0\n";
}

This will explicitly print the character à you requested; in fact, that's also how your browser understands it, which you can easily verify by putting into e.g. some unicode character search, which will result in LATIN SMALL LETTER A WITH GRAVE, with the code U+00E0 which you can spot in the code above.

In your example, there's no difference between using a signed or unsigned char; the byte value 133 gets written to the terminal, but the way it interprets it might differ from machine to machine, basing on how it's actually set up to interpret it. In fact, in a UTF-8 console, this is simply a wrong unicode sequence (u"\0x85" isn't a valid character) - if your OS was switched to UTF-8, that might be why you're seeing no output.

Upvotes: 3

anastaciu
anastaciu

Reputation: 23802

You can try to use static_cast

std::cout << static_cast<unsigned char>(133) << std::endl;

Or

std::cout << static_cast<char>(133) << std::endl;

Since in mine all of this is working, it's hard to pinpoint the problem, the common sense would point to some configuration issue.

Upvotes: 0

Related Questions