How would I go about converting a string to int?

116 Views Asked by At

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.

1

There are 1 best solutions below

0
Displayed name On

So, VS is marking it as a missing semicolon because there is an extra one. On line 19, else (num1 == num2); { should be else (num1 == num2) {. Notice how there is a semicolon before the bracket. String problem You are trying to return a std::string from int getMax(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:

#include <iostream>
#include <string>

using namespace std;

int getMax(int num1, int num2){

    int result;


    if (num1 > num2) {
        result = num1;
    }
    else if (num1 < num2) {
        result = num2;
    }
    else (num1 == num2) {
        result = -1;
    }



    return result;
}

int main(){

    string areEqual("The numbers are equal");
    switch(getMax(5,5)){
        case 5:
        cout << 5;
        break;
        case -1;
        cout << areEqual;
        break;
        default:
        cout << "Something else?";
    }
    
    
    return 0;
}

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::string from getMax. Cout it like normal and convert the integers from integers to strings using std::to_string. Welcome to C++! I hope you enjoy using this beautiful language!