Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return string that contains string/int variables

Tags:

c++

string

For example, if I have this little function:

string lw(int a, int b) {    
    return "lw $" + a + "0($" + b + ")\n";
}

....and make the call lw(1,2) in my main function I want it to return "lw $1, 0($2)".

But I keep getting an error: invalid operands of types ‘const char*’ and ‘const char [11]’ to binary ‘operator+’

What am I doing wrong? I pretty much copied an example from class, and changed it to suit my function.

like image 877
Rima Avatar asked Nov 28 '11 14:11

Rima


People also ask

How do you return a string in int?

Use Integer.parseInt() to Convert a String to an Integer This method returns the string as a primitive type int. If the string does not contain a valid integer then it will throw a NumberFormatException.

Can int function return string?

You can't return a string from a function having int return type .

Can a string have an int?

The answer to your question is "no". A number can have one of several C types (e.g. int , double , ...), but only one of them, and string is not a numeric type.

How do you return a string to an int in Python?

Use the syntax print(int("STR")) to return the str as an int , or integer. How to Convert Python Int to String: To convert an integer to string in Python, use the str() function. This function takes any data type and converts it into a string, including integers.


2 Answers

You are trying to concatenate integers to strings, and C++ can't convert values of such different types. Your best bet is to use std::ostringstream to construct the result string:

#include <sstream>

// ...

string lw(int a, int b)
{
    ostringstream os;
    os << "lw $" << a << "0($" << b << ")\n";
    return os.str();
}

If you have Boost, you can use Boost.Lexical_cast:

#include <boost/lexical_cast.hpp>

// ...

string lw(int a, int b)
{
    return
        string("lw $") +
        boost::lexical_cast<std::string>(a) +
        string("0($") +
        boost::lexical_cast<std::string>(b) +
        string(")\n");
}

And now with C++11 and later there is std::to_string:

string lw(int a, int b)
{
    return
        string("lw $") +
        std::to_string(a) +
        string("0($") +
        std::to_string(b) +
        string(")\n");
}
like image 64
Some programmer dude Avatar answered Dec 03 '22 20:12

Some programmer dude


#include <sstream>

string lw(int a, int b) {    
    std::string s;
    std::stringstream out;
    out << "lw $" << a << "0($" << b << ")" << endl;
    s = out.str();
    return s;
}
like image 30
Igor Avatar answered Dec 03 '22 20:12

Igor