skip to Main Content

I encountered a strange issue while working on a C++ program with VisusalStuidio 2021. When I used cout << ‘/n’;, I expected it to simply print /n or values in ASCII(47110), but instead, it printed 12142. This behavior is confusing and I couldn’t find a clear explanation for it.

I’ve tried to go googling but the only answers are very sketchy, so I’d appreciate a detailed answer, thanks!Hope someone can help me。

2

Answers


  1. you are seeing multicharacter constant, look in character_constant and search for multicharacter constant.

    1. multicharacter constant, e.g. ‘AB’, has type int and implementation-defined value.

    you are just seeing the concatenation of the bytes of both / and n converted to an int, you can print them in hex to see their hex representation is equivalent.

    #include <iostream>
    
    int main()
    {
        std::cout << '/n' << std::endl;
        std::cout << std::hex << '/n' << std::endl;
        std::cout << std::hex << static_cast<int>('/') 
          << std::hex << static_cast<int>('n') << std::endl;
    }
    
    12142
    2f6e
    2f6e
    
    Login or Signup to reply.
  2. Just use the double quotes:

    #include <iostream>
    
    using namespace std;
    
    int main() {
       cout<<"/n";
    
        return 0;
    }
    

    For anyone wondering why the value is 12142, the likely answer is that in the OP’s implementation, ‘/’ has the integral value 47, ‘n’ has the integral value 110, and these are "concatenated" into an int a la <47><110> (leaving endianness out of the picture), giving a value of 47*2^8 + 110 = 12142

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search