0
#include<bits/stdc++.h>
using namespace std;

int main()
{
    string str = "Hello"; 
    string s = str[0] + str[1];  
    cout << s;
    return 0;
}

Why does this code gives an error, even if we can concatenate strings?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Pratik
  • 11
  • 3
    Because `str[0]` and `str[1]` are single `char` entities. And adding two `char` values is simple and plain integer addition. – Some programmer dude Sep 06 '21 at 07:25
  • 8
    By the way, [never include ``](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h), and [`using namespace std;` is a bad habit](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice). – Some programmer dude Sep 06 '21 at 07:25

2 Answers2

3

the reason this fails

std::string s = str[0] + str[1];

is because str[0] and str[1] return a char (H and e):

std::string s = 'H' + 'e';

and adding two chars will not concatenate them, instead their values will be added together. Every character has an assigned number (look up ASCII table)

std::string s = 72 + 101;

and this will fail, as assigning the number 173 to a string doesn't really make sense to the compiler.


there are multiple ways to concatenate variables together, in this case the most simple solution would be

std::string s { str[0], str[1] };

This will be limited to chars though, so you couldn't say { str[0], str[1], 500 }. Therefore the general way to concatenate any number of data, is to use std::ostringstream, found in the header <sstream>. This how it is used:

std::ostringstream stream;
stream << str[0] << str[1] << 500;

std::string s = stream.str();

Read here why using namespace std; is considered bad practice and here why <bits/stdc++.h> is to be avoided.

Stack Danny
  • 7,754
  • 2
  • 26
  • 55
2

str[0] and str[1] are giving you characters, not strings. Adding them gives you another character, which cannot be casted to a string.

You can construct a new string with a substring of the first part of the string you want to concatenate, and then insert the substring of the second part of the string you want to concatenate, like so:

// Construct new string that contains the first character of str
string s(str.begin(), str.begin() + 1);

// Add the second character of str onto the end of s
s.insert(s.end(), str.begin() + 1, str.begin() + 2);
fortytoo
  • 452
  • 2
  • 11
  • 2
    Or you could just do `std::string s = std::string({str[0], str[1]});` – t.niese Sep 06 '21 at 07:36
  • 1
    Yes, if you're only doing one character at a time. Better yet would be `string s{ str[0], str[1] };` Gets rid of the temporary. The iterator thing is just for scalability. Of course, you'd have to change the `+ 1`s and the `+ 2`s, but still. – fortytoo Sep 06 '21 at 07:41