Single quote in cpp cout

On pages 72-73 of programming: principles and practice using C ++:

We saw that we cannot directly add characters or compare double with int. However, C ++ provides an indirect way to do both. When necessary, char is converted to int and int is converted to double. For instance:

char c = 'x'; 
int i1 = c; 
int i2 = 'x'; 

Here, both i1 and i2 get a value of 120, which is the integer value of the character "x" in the most popular 8-bit character set, ASCII. This is a simple and safe way to get a numeric representation of a character. We call this char -to-int conversion safe because no information is lost; that is, we can copy the resulting int back into char and get the original value:

char c2 = i1; 
cout << c << ' << i1 << ' << c2 << '\n';

Opens x 120 x

, . , x540818464x.

+4
5

, .

cout << c << ' ' << i1 << ' ' << c2 << '\n';
+4

' << i1 << ' - , int , .

, : cout << c << ' ' << i1 << ' ' << c2 << '\n';

.

+5

, , :

cout << c << ' ' << i1 << ' ' << c2 << '\n';

, :

cout << c << ' << i1 << ' << c2 << '\n';

' << i1 << ' ( ) , int , .

[lex.ccon]/2:

, c- char, . [...] , int , .

Its use is relationally rare, I personally saw it as a way of defining arbitrary constants, for example, in

enum state { wait = 'wait', start = 'start', /*...*/ };
+3
source

You should try this code (see below). There is a typo that you or this book made.

#include <iostream>
using namespace std;

int main() {
    char c = 'x';
    int i1 = c;
    int i2 = 'x';
    char c2 = i1;
    std::cout << c << ' ' << i1 << ' ' << c2 << '\n';
    return 0;
}

Result:

enter image description here

+1
source

Using single quotes, we can print the value of ascii. Thus, the ascii value of the entire expression was printed.

Thanks, hope this helps

0
source

Source: https://habr.com/ru/post/1691923/


All Articles