Search code examples
c++windowsshellexecute

How to make a function so I can type what browser I want to open?


What is wrong with my code? I am trying to make a program where you can type what browser you want to open. VC++ keeps underlining equal sign in if statement.

#include <iostream>
#include <Windows.h>
using namespace std;

void OpenBrowser(string browser) {
    ShellExecuteA(NULL, "open", browser.c_str(), NULL, NULL, SW_MAXIMIZE);
}

int main() {
    char a;
    std::cout << "What is your favourite browser?\n" << std::endl;
    std::string input;
    std::cin >> a;

    if (a = "firefox") {
        OpenBrowser("firefox");
    }

    else {
        OpenBrowser("chrome");
    }

    system("pause");
    return 0;
}

Solution

  • There are two main errors to note in the code.

    1. Allocating variable a on the stack, please notice it's a char, meaning that you ask for a single (1) byte to be allocated on the stack (probably 4 because of alignment) to hold the variable that will be input. So for the variable to be able to hold a string like "firefox" or "chrome" we will need more data, for instace, char a[MAX_PATH + 1];

    2. As been said, the = operator will assign a with the pointer to the "firefox" string, this will not work for two reasons, one being that the type char cannot hold a pointer due to it's size, the second reason being that the types are not the same (char - the input and const char* - "firefox"). To add to that, if we would change the type of a to const char* changing = to == will not work either because in that case you are trying to check for equality between a pointer in your data section ("firefox") and a pointer to data on the stack (variable a), the == operator will simply check if the pointers are equaly, ie pointing to the same place in memory. So the easy way to solve this would be to use strcmp, strcmp on msdn.

    Tl;dr:

    #include <iostream>
    #include <Windows.h>
    
    using namespace std;
    
    void OpenBrowser(string browser) {
        ShellExecuteA(NULL, "open", browser.c_str(), NULL, NULL, SW_MAXIMIZE);
    }
    
    int main() {
        char a[MAX_PATH + 1];
        std::cout << "What is your favourite browser?\n" << std::endl;
        std::string input;
        std::cin >> a;
    
        if (!strcmp(a, "firefox")) {
            OpenBrowser("firefox");
        }
    
        else {
            OpenBrowser("chrome");
        }
    
        system("pause");
        return 0;
    }