question

FredericReinhardt-6870 avatar image
0 Votes"
FredericReinhardt-6870 asked YujianYao-MSFT commented

Visual Studio 2019 C++: Why do char and string literals with non-ASCII characters have different values depending on the source file?

Why does the value of c after the assignment

char c='ü';

depend on whether it appears in the source file 'CharTest.cpp' with the main()-function or in a different source file?

You can test this in Visual Studio 2019 with the following 3 files for which i get the output
f: -4
main: -68

even though the values should be the same.

 // TU.h
 void f();
    
 // TU.cpp
 #include <iostream>
 void f()
 {
     char c = 'ü';
     int i(c);
     std::cout << "f: " << i << "\n";
     return;
 }
    
 //  CharTest.cpp
 #include <iostream>
 #include "TU.h"
    
 int main()
 {
     char c = 'ü';
     f();
       
     int i(c);
    
     std::cout << "main: " << i << "\n";
    
     return 0;
 }

c++
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Presumably because you have different encodings for those files?

1 Vote 1 ·
YujianYao-MSFT avatar image
1 Vote"
YujianYao-MSFT answered

Hi @FredericReinhardt-6870,

Tried setting the Code Page to UTF-8 and I got the following results:

202197-code.png

202170-2019.png

Best regards,

Elya



code.png (4.6 KiB)
2019.png (26.9 KiB)
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

FredericReinhardt-6870 avatar image
0 Votes"
FredericReinhardt-6870 answered YujianYao-MSFT commented

Thank you! That worked. I have now also figured out that one can change the encoding in the "save as"-dialogue by clicking on the little arrow besides "Speichern" (in the german version).

I think Visual Studio automatically chose different encodings for the two files when i generate a new project. It chose UTF-8 for the main source file, because it was generated with german comments containing Umlaute like "ü", while it chooses ANSI encoding for the other files.

202247-image.png



image.png (35.5 KiB)
image.png (40.2 KiB)
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Click the drop arrow on the save button to get the the encoding option.

1 Vote 1 ·

Hi @FredericReinhardt-6870,

Glad to know you've found the solution to resolve this issue! please click "Accept Answer". It will also help others to solve a similar issue.

0 Votes 0 ·