- 1

Dumb questions

What is the output of adding a float to a string? Why does it matter all we need to know is that it's nothing useful. Why does it matter whatever it returns would never be useful.

28th Dec 2018, 6:53 AM
John N Anderson
John N Anderson - avatar
2 Answers
+ 5
Very philosophical question! First, let's ask the compiler guy the question... Hey man, could you please run this code... #include <iostream> #include <string> using namespace std; int main() { string s = "I'm dumb!"; float f = 3.14f; cout << s + f; } HELL NO! error: no match for 'operator+' (operand types are 'std::string {aka std::basic_string<char>}' and 'float') Why?! BECAUSE THEY CAN'T MATE!!! IT'S IMPOSSIBLE FOR A CAT AND AN ELEPHANT TO S** TOGHEDR! So, Is there any solution to this MATE problem? YUP! CONVERT FLOAT TO STRING! How? #include <iostream> #include <string> using namespace std; int main() { string s = "I'm dumb!"; float f = 3.14f; cout << s + to_string(f); } Output: I'm dumb!3.140000
28th Dec 2018, 7:51 AM
Babak
Babak - avatar
+ 4
In one programming language, you get a 'useless' result, in another language it might make your program crash or it won't even compile. It's definitely useful to know what happens in these scenarios. It helps you understand how the language works, how you can debug your codes efficiently etc.
28th Dec 2018, 7:12 AM
Anna
Anna - avatar