Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single Quote in cpp cout [closed]

Tags:

c++

cout

From page 72–73 of Programming: Principles and Practices using C++:

We saw that we couldn’t directly add chars or compare a double to an int. However, C++ provides an indirect way to do both. When needed, a char is converted to an int and an int is converted to a double. For example:

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

Here both i1 and i2 get the value 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 of getting the 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 a char and get the original value:

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

This will print x 120 x

I do not understand the single quote use here. When I try it, it prints x540818464x.

like image 767
Nour Avatar asked Dec 11 '22 08:12

Nour


1 Answers

' << i1 << ' is a multicharacter literal, has type int and implementation-defined value.

You probably want: cout << c << ' ' << i1 << ' ' << c2 << '\n';

with regular character space.

like image 139
Jarod42 Avatar answered Jan 06 '23 13:01

Jarod42