Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++17

c++14

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'; 
like image 998
Denis Sablukov Avatar asked Oct 22 '18 14:10

Denis Sablukov


2 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; 
like image 132
Alexander Petrenko Avatar answered Sep 18 '22 17:09

Alexander Petrenko


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

like image 32
molbdnilo Avatar answered Sep 20 '22 17:09

molbdnilo