create a string by adding other string elements?

is there any possibility to add few elements of other string to get a new string?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string.h>
using namespace std;

int main()
{
    string A = "look forward to";
    string B = "always";
    string C = "of your life";
    string D = "every moment";

    string E = B + " " + A; //output is "always look forward to"
    string F = A[0] + A[1] + A[2] + A[3]+ " " +C[1]+C[0]+C[6] + " " + D; 
    //output should be "look for every moment"

    cout << "E: " << E << endl;
    cout << "F: " << F << endl;
}


E is okay, but when I tried F it ended up with an error:
error: invalid operands of types 'const char*' and 'const char [2]' to binary 'operator+'

Last edited on
You should read about operator overloading to understand why you got the error.

To answer your question: A[0] really == 'l', which is a single character, not the first word as you wanted. Want individual words? You can tokenize a string into words by using a istringstream and the extraction operator.
The error means that the compiler doesn't know of and operator "+" which has a const char* or string on one side and a char on the other.
 
string F = string("") + A[0] + A[1] + A[2] + A[3]+ " " +C[1]+C[0]+C[6] + " " + D; 


should fix that.
I've had this problem before too. I'm a sub-par programmer who doesn't really understand the responses above. I've been able to circumvent this problem by doing the following, although next time I'll try hanst99's solution. (If his thing works, do that).

1
2
3
4
5
6
7
8
9
10
string F = A[0];
F+=A[1];
F+=A[2];
F+=A[3];
F+=" ";
F+=C[1];
F+=C[0];
F+=C[6];
F+=" ";
F+=D;


thanks! hanst99's method is working... mind explain what is the meaning of string("")?
Basically it makes a string with no data.

Technically, the only point is to allow the compiler to use the operator + (std::string, char) overloads. (operator +(char, std::string) doesn't exist)
Topic archived. No new replies allowed.