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

100 views Asked by At

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;
}
2

There are 2 answers

1
papadp On BEST ANSWER

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;
}
1
AudioBubble On

Here is an example on how to open a browser using a user defined function and a call to ShellExecute:

#include <iostream>
#include <Windows.h>

void openBrowser(const std::wstring& browser)
{
    ShellExecute(0, NULL, browser.c_str(), NULL, NULL, SW_SHOW);
}
int main()
{
    openBrowser(L"C:\\Program Files\\Mozilla Firefox\\firefox.exe");
    return 0;
}