user1553248
user1553248

Reputation: 1204

String as a parameter (C++)

Is this example code valid?

std::string x ="There are";
int butterflies = 5;
//the following function expects a string passed as a parameter
number(x + butterflies + "butterflies");

The main question here is whether I could just pass my integer as part of the string using the + operator. But if there are any other errors there please let me know :)

Upvotes: 0

Views: 457

Answers (5)

Bình Nguyên
Bình Nguyên

Reputation: 2352

You can use stringstream for this purpose like that:

#include <iostream>
#include <sstream>
using namespace std;

int main()
{
    stringstream st;
    string str;

    st << 1 << " " << 2 << " " << "And this is string" << endl;
    str = st.str();

    cout << str;
    return 0;
}

Upvotes: 2

RageD
RageD

Reputation: 6823

A safe way to convert your integers to strings would be an excerpt as follows:

#include <string>
#include <sstream>

std::string intToString(int x)
{
  std::string ret;
  std::stringstream ss;
  ss << x;
  ss >> ret;
  return ret;
}

Your current example will not work for reasons mentioned above.

Upvotes: 1

Scott Hunter
Scott Hunter

Reputation: 49803

More C than C++, but sprintf (which is like printf, but puts the result in a string) would be useful here.

Upvotes: 1

Ivan Kruglov
Ivan Kruglov

Reputation: 753

No, it wouldn't work. C++ it no a typeless language. So it can't automatically cast integer to string. Use something like strtol, stringstream, etc.

Upvotes: 1

Antimony
Antimony

Reputation: 39451

C++ doesn't do automatic conversion to strings like that. You need to create a stringstream or use something like boost lexical cast.

Upvotes: 4

Related Questions