#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?
#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?
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 char
s 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 char
s 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.
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);