Is there any way to get char by auto type deduction using decimal ASCII Code?

Viewed 1478

For example 'a' has ASCII code 97 and we could use

char ch = 'a';

or

char ch = 97;

With auto we could write

auto ch = 'a';

for the first case, but how to get char variable by numerical ascii code during deduction?

This doesn't work for me:

auto ch = '\97';
4 Answers

You have to use octal or hex value for escape sequence

auto ch  = '\141';
auto ch2 = '\x61';

For more info https://en.cppreference.com/w/cpp/language/escape

If you want to use decimal values, you have two options:

  1. Cast to char

    auto ch = static_cast<char>(97);
    
  2. User-defined literals

    char operator "" _ch(unsigned long num)
    {
         return static_cast<char>(num);
    }
    //...
    auto ch = 97_ch;
    

There's no decimal escape, but you can use hexadecimal: '\x61', or octal, '\141'.
If you really need decimal, you need to cast; char{97}.

There is no integral literal that specifies a char. You have to explicitly name the type, e.g.

auto ch = char{97};
Related