How to return a string containing string / int variables

For example, if I have this little function:

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

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

But I get an error all the time: invalid operands of types 'const char*' and 'const char [11]' to binary 'operator+'

What am I doing wrong? I pretty much copied the example from the class and modified it to fit my function.

+6
source share
5 answers

You are trying to combine integers into strings, and C ++ cannot convert values โ€‹โ€‹of such different types. It is best to use std::ostringstream to build 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 versions of std::to_string :

 string lw(int a, int b) { return string("lw $") + std::to_string(a) + string("0($") + std::to_string(b) + string(")\n"); } 
+10
source
 #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; } 
+2
source

Use ostringstream:

 #include <sstream> ... string lw(int a, int b) { std::ostringstream o; o << "lw $" << a << "0($" << b << ")\n"; return o.str(); } 
+2
source

You cannot add string literals (such as hello) to integers. This is what the compiler tells you. This is a partial answer to your question. See how to accomplish what you want in other posts.

+1
source

To understand this question, you should know that in C ++ string literals such as "lw $" are considered as const char[] as inherited from C. However, this means that you only get operators that are defined for arrays , or in this case, the case of changing the array-to-pointer.

So what happens, you have a string literal, and then add an integer to it, creating a new pointer. Then you try to add another string literal, which again degrades to char* . You cannot add two pointers together, which then generate the error you see.

You are trying to format integers in string format with some separator text. In C ++, the canonical way to do this is with stringstreams:

 #include <sstream> string lw(int a, int b) { std::ostringstream os; os << "lw $" << a << "0($" << b << ")\n"; return os.str(); } 
0
source

Source: https://habr.com/ru/post/902562/


All Articles