0

Below is a cout of a c++ statement:

cout << "TESTING" + 2 << endl;

I understand why this statement will print out sting. But the question I have is if I do the code below it will cause an error. I don't understand why as this is the same thing. Sorry for a basic question I am new to c++.

 string t = "TESTING";
 cout << t + 2 << endl;

Thanks in advance for any help. :)

Pouria
  • 72
  • 6
  • The actual error message not included in your post generated from the second , should be entirely telling as to what the problem is. There is no `operator +` overload accepting `std::string&, int` or convertibles therein. – WhozCraig Nov 04 '19 at 16:23

2 Answers2

3

This is an interesting case. I'm not sure if you've actually printed the result of your first statement or not, but if you do you see that you are actually getting "STING" and not "TESTING2", or something like that!

There are a few things going on here. In your first statement, you are constructing a string using a string literal. In this case, C++ create a const char[N] and put your string into it. Since char[N] is technically an array (and array is a pointer), the operator + acts as increment and the result of "TESTING" + 2 is actually a pointer to the second element of "TESTING", which is "STING". You'll not see any errors, because C++ thinks that what's you wanted to do.

In your second statement, you are telling C++ that I want a std::string object. The std::string is by design safer and will nag at you if you try to add anything other than a string to it. So, when you do, you get an error. For your second statement to work as intended, you should write t + std::to_string(2).

Amir
  • 1,087
  • 1
  • 9
  • 26
  • 1
    *"and array is a pointer"* - should have just left that out. It's simply not true. Rather, in an appropriate expression context (such as this), the array id converts to a *temporary* pointer-to type (`char`), where the ensuing pointer arithmetic of `+ 2` is viable. Also, "anything other than a string" in the third paragraph is not accurate, as multiple [`operator +` overloads exist](https://en.cppreference.com/w/cpp/string/basic_string/operator%2B), including just `char` (so `m + '2'` would be acceptable), as well as `const char*` (so `m + "2"` would likewise pass). – WhozCraig Nov 04 '19 at 16:55
2

It is important to know the difference between string and char types. String is a class that manages string of characters. And char[] is an array of characters. Refer this question for the explanation. In your case the code will work if you do:

#include <iostream>

int main ()
{
char t[] = "TESTING";
std::cout << t + 2 << std::endl;
return 0;
}

If you want to concatenate string with int then you should explicitly convert it:

#include <iostream>

int main ()
{
std::string m = "Testing ";
std::cout << m + std::to_string(2) << std::endl;
return 0;
}
R4444
  • 2,016
  • 2
  • 19
  • 30