I'm watching a Youtube guide about "if statements" and wanted to experiment a little but by adding a third outcome that the numbers are equal but I keep getting thrown this error:
No suitable conversion function from "std::string to "int" exists
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int getMax(int num1, int num2){
int result;
string areEqual("The numbers are equal");
if (num1 > num2) {
result = num1;
}
else if (num1 < num2) {
result = num2;
}
else (num1 == num2); {
* return string(areEqual);
}
return result;
}
int main(){
cout << getMax(5, 5);
return 0;
}
This is what I currently have, I tried looking into the std::stoi function but the resource I found on cppreference.com was pretty confusing to me.
Visual studio also seems to think there is an error on line 20 claiming that there is a missing semicolon, Not sure why though ( I highlighted the line with a *)
apologies if any of this is worded poorly or completely incorrect, I've only just started with c++ yesterday.
So, VS is marking it as a missing semicolon because there is an extra one. On line 19,
else (num1 == num2); {should beelse (num1 == num2) {. Notice how there is a semicolon before the bracket. String problem You are trying to return astd::stringfrom intgetMax(int num1, int num2). To clarify: It would be like putting a wrench in the works, so to speak. What you need is not a way to convert a complex, text string like that to an integer, you need a way to get it out of that function. While there are many ways to do this (void pointers, returning a string, special codes(the worst way)), the rough and gritty solution is:This, of course is NOT a good solution and should not be considered for any applications. The only reason I'm writing this code is because it seems to just be a small example. In real code, consider returning a
std::stringfromgetMax. Cout it like normal and convert the integers from integers to strings usingstd::to_string. Welcome to C++! I hope you enjoy using this beautiful language!