-6

When i try to add text to string i get random values.

Code:

#include <iostream>

using namespace std;

int main()
{
    cout << "333" + 4;
}

I get some random text like:↑←@

Qeaxe
  • 71
  • 8

4 Answers4

5

"333" is a const char [4] not std::string as you might expect(which by the way still doesn't have operator+ for int). Adding 4, you're converting it to const char * and then moving the pointer by 4 * sizeof(char) bytes, making it point to memory with garbage in it.

Community
  • 1
  • 1
1

It happens because those are two different types and the adding operator does not work as you may expect.

If you intend to concatenate the string literals "333" with the int value of 4 than you should simply use count like:

cout << "333" << 4; // outputs: 3334

If you want to display the sum, than use string to int conversion with the stoi() function.

cout << stoi("333") + 4;  // outputs: 337

Note: When using stoi(): If the string also contains literals, than the conversion will take the integer value from the beginning of the string or will raise an error in case the string begins with literals:

cout << stoi("333ab3") + 4; // same as 333 + 4, ignoring the rest, starting a
cout << stoi("aa333aa3") + 4; // raise error as "aa" can't be casted to int
Codrut TG
  • 648
  • 7
  • 10
  • They're not incompatible, but the operation that is performed is pointer arithmetic, not addition or concatenation. – Quentin Nov 03 '16 at 13:00
  • OP wants to add text to string, not number to number – Slava Nov 03 '16 at 13:16
  • @Quentin they are not incompatible, that's right, but even if this is a legit pointers arithmetic operation, you should see that is not the one the asker expects. So I was meaning they don't fit for getting the expected result. As long as the result is not the one it was expected you can be sure he doesn't wanted pointer arithmetics (even the asker haven't specified it). So, my point was that you can not combine dogs with birds to get planes... Answer updated, thanks for pointing. It may have mislead others, maybe, as I wasn't so explicit. – Codrut TG Nov 03 '16 at 16:04
0

As you want to add text to text, solution would be to use proper types:

cout << std::string( "333" ) + "4";

or for c++14 or later:

using namespace std::string_literals;
cout << "333"s + "4"s;
Slava
  • 40,641
  • 1
  • 38
  • 81
-3

I honestly do not know what you are trying to achieve by adding int to string. In case you want to add 333+4, you need to Parse string in to int like this :

edit:Typo #include

using namespace std;

int main()
{
    cout << std::stoi("333") + 4;
}
Demon
  • 109
  • 6