0

I have this (example) code:

#include <iostream>
#include <string>

using namespace std;
int main()
  {
    string myvar = "string" + 5;
    cout<<myvar<<endl;
    return 0;
  }

I want this to print string5, like it would in Python, but instead, it prints g. How do I get C++ to do this? I haven't gotten anywhere with googling.

I'm pretty new to C++

Ali
  • 2,702
  • 3
  • 32
  • 54
  • You may want to refresh your memory: this doesn't work in Python either! – Mark VY Dec 07 '18 at 02:05
  • Nor would it in Perl, but it would work in JavaScript. – melpomene Dec 07 '18 at 02:07
  • If you're new to C++, a good thing to learn now would be to never use `endl`. If you want to portably print a newline, use `<< '\n'`; if you want to flush a stream, use `std::flush`. – melpomene Dec 07 '18 at 02:08
  • But you often want both, so you might as well use endl. – Mark VY Dec 07 '18 at 02:13
  • @MarkVY If you want both, the best solution is `... << '\n' << std::flush`. But really you shouldn't need to flush all that often. – melpomene Dec 07 '18 at 02:16
  • @MarkVY this would work in python, but not implicitly. You'd need to also convert `5` into a string through the `str()` function, or just surround it with quotes. All my point was was that you can simply add items to each other in python for them to combine. – mechanical_mechanic Dec 07 '18 at 04:52

1 Answers1

1

You can use this:

string myvar = "string" + std::to_string(5);
cout<<myvar<<endl; // prints string5
Gauravsa
  • 6,330
  • 2
  • 21
  • 30
  • When I run this I get "'to_string is not a member of 'std'". When I remove `std::` I get "'to_string' was not declared in this scope". Am I on an outdated client? I'm using Dev-C++. – mechanical_mechanic Dec 07 '18 at 04:59
  • please refer here: https://stackoverflow.com/questions/35874215/dev-c-to-string-is-not-a-member-of-std-error?lq=1 – Gauravsa Dec 07 '18 at 05:03
  • Need to change the language standard to ISOC++11 or GNUC++11 in the compiler settings. – Gauravsa Dec 07 '18 at 05:03