1

I'm pretty new to C++ and I'm trying to write a simple function to take user input and navigates to the site, adding the https://www. at the beginning of the string, but I cant quite figure out how to call the link within the quotes (or otherwise) within the system function. I come from python so I'm used to being able to use an f string for something like this, and I'm not sure if there's a C++ equivalent, here's my code:

#include <fstream>
#include <iostream>
using namespace std;

void openChrome(string site){
    string link = "https://www." + site;
    system("open -a 'Google Chrome' //link//");
    cout << link;
    }


int main()
{
    openChrome("apple.com");
}

the cout correctly outputs the full site link, I tried moving the link var outside of the quotes, and that throws an error, so is there something obvious that I'm missing?

EDIT: The issue I'm having isn't with the string concatenation, rather if I try to call the link variable there, it just outputs as the literal since it's in quotes and interpreted directly by the terminal, and throws an error that says 'link' isn't a valid link

ku3ngu
  • 13
  • 4
  • It seems you have the string concatenation down. Please refer to [this question](https://stackoverflow.com/questions/17347950/how-do-i-open-a-url-from-c). –  May 21 '20 at 20:26
  • Does this answer your question? [How do I open a URL from C++?](https://stackoverflow.com/questions/17347950/how-do-i-open-a-url-from-c) –  May 21 '20 at 20:27
  • [Why `system` is evil](http://www.cplusplus.com/articles/j3wTURfi/) – lost_in_the_source May 26 '20 at 22:41

1 Answers1

0

I made a few changes to your program:

#include <fstream>
#include <iostream>
using namespace std;

void openChrome(string site) {
    string link = "https://www." + site;
    string script = "open -a \"Google Chrome\" " + link;
    const char *command = script.c_str();
    system(command);
    cout << link;
}
int main()
{
    openChrome("apple.com");
}
petrubear
  • 616
  • 5
  • 6
  • this works perfectly, thank you! can you explain the things you changed please? – ku3ngu May 27 '20 at 12:58
  • first I replaced //link// with the url you create in the variable link and concatenate it to the command you want to execute with +, now I have the command I want to execute on the variable script, but, the system call doesn't accept strings, its signature is "int system(const char *command)" so I convert the script string to a char* with the function c_str() and I assign it to the variable command which I pass to the system() function – petrubear May 27 '20 at 13:05