D
D
DVoropaev2018-02-19 01:29:24
C++ / C#
DVoropaev, 2018-02-19 01:29:24

Why are strings processed incorrectly in C++, and how can I fix it?

instead of Russian letters from s1 to s2, rubbish is copied.
s1 is displayed normally, but s2 is not.

#include <iostream>
#include <string>

using namespace std;

int main(){
string s1 = "АБВГД";
string s2 = "ABCDE";
cout << s1 << endl << s2 << endl;
for(int i = 0; i < 5; i++)
  s2[i] = s1[i];
cout << s1 << endl << s2 << endl;
return 0;
}

Job:

$ g++ ./st.cpp $
./a.out
ABCDE
ABCDE ABCDE AB

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2018-02-19
@alexr64

Are you working with Unicode and Russian letters take not 1 byte, but 2?

S
Stanislav Makarov, 2018-02-19
@Nipheris

cppwhispers.blogspot.ru/2012/11/unicode-and-your-a...
In GCC, on modern systems, the default encoding for char string literals is UTF8.
And in order not to depend on the compiler and the environment, smoke modern theory: one , two .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question