How to assign a string of type string value of 2 characters of type char (array elements)?

string arr [ 10 ]; // к примеру заполнены символами string c = arr [ 1 ] + arr [ 2 ]; // так выдает ошибку 
  • Do you understand that arr[10] is an array of strings, not characters? What kind of error do you get? (learn to read and understand error messages!) - user6550
  • I understand this perfectly, but when you write 1 character in a string, it is considered as char. - csmirror

2 answers 2

Through torture and telepathy, it was found that the question should actually be:

Why does the code std::string c = 'c' not work?

Answer: because there is no operator for assigning a character value to a string. In a very rough approximation, you can do this:

 std::string c; c.push_back( arr[1][1] ); c.push_back( arr[2][1] ); 

(I hope the units in the indices are not a mistake and everyone understands that the indices here are 0-based).

Well, for details, read the documentation . Preferably, before writing code, and before asking questions :)

  • std :: string arr [10]; arr [1] = "123"; arr [2] = "abc"; std :: string c = arr [1] [1] + arr [2] [1]; std :: cout << c << '\ n'; This one doesn't work. - csmirror
  • one
    We continue to pull out information under torture: did you read what the compiler wrote to you? Do you understand? What does he say to you: std::string c = 'a' ? - user6550

std :: string arr [10]; arr [1] = "123"; arr [2] = "abc"; std :: string c = arr [1] [1] + arr [2] [1]; std :: cout << c << '\ n'; This one doesn't work.

You can add individual characters to the string via push_back:

 std::string arr[10]; arr[1] = "123"; arr[2] = "abc"; std::string c; c.push_back(arr[1][1]); c.push_back(arr[2][1]); std::cout << c << '\n'; 

Result:

 2b