[cs23021] concatanate strings with chars

Mikhail Nesterenko mikhail at cs.kent.edu
Wed Oct 13 22:38:02 EDT 2010


> Mikhail,
> 
> We spoke today after class regarding string concatanation. The following
> code does not work as expected.
> ...

There is a bit of an fine print with concatenation. A least one of the
operands have to be a string variable. You cannot concatenate two
literal string constants or a literal string constant and a character.
This has to do with how the concatenation operator is implemented. If
you remind me, I'll explain it when we study objects later in the
course. The below code illustrates the idea:


--------------
#include <iostream>
#include <string>

using namespace std;

int main () {
  string s1;

  s1 = "hell"; // this is allowed
  // s1 = "hell" + "o"   <-- this is not allowed!
  s1 = s1 + 'o'; // this is allowed

  cout << s1 << endl;
}
----------------

Thanks,
--
Mikhail

 PS: "concatenation" is spelled with an "e"



More information about the cs23021-2 mailing list