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.
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.
You can't return a string from a function having int return type .
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.
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.
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");
}
#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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With