-2

I need to open several images from a website generating the url of the image with a for cycle - all the urls look the same but for the final number.

system("open") works fine for a single url, but I don't know how to pass the variable referring to the number of the image inside the command, being it a string.

#include <iostream>
#include <stdlib.h>

using namespace std;

int main()
{
    for (int i = 1; i <= 13; i++)
    {
        system("open http://www.site/images/image-[how do I pass i here??].jpg");
    }
}

[Edit] I'm working on MacOS.

DavideL
  • 294
  • 1
  • 3
  • 15

1 Answers1

1

You should build dynamically the C string passed to system.

For example:

for (int i=1; i<=13; i++) {
  char cmdbuf[80];
  snprintf(cmdbuf, sizeof(cmdbuf), "open http://www.site/images/image-%d.jpg", i);
  int notok = system(cmdbuf);
  if (notok) break;
}

the above is actually C code (which, with appropriate #include-s, would work in C++). If you want genuine C++ code you might use some std::ostringstream to build some std::string (and convert it into a C string using its c_str member function before passing that to system)

Read about snprintf in C and in C++. C and C++ are different languages.

In C++, std::system is provided with <cstdlib> (which you should use instead of <stdlib.h> which is a C standard header).

BTW, you might be interested by HTTP server libraries such as libonion and by HTTP client libraries such as libcurl. You'll better understand much more about the HTTP protocol.

Your above program is better and faster written as a shell script. For your particular case it would be faster (to write), and more robust (even if perhaps it runs a few milliseconds slower). Notice that open is not a standard POSIX program (on Linux, you would use xdg-open instead) and might not exist on Windows (which I don't know at all).

Notice also that neither the C standard nor the POSIX standard guarantee that the user of your program has a screen. If you run your program on some datacenter machine, you might be disappointed.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • 1
    Can confirm, no joy with `open` on Windows 10 at least – Lightness Races in Orbit Feb 02 '19 at 18:32
  • Don't get me wrong, I do appreciate the detailed and insightful answer. But as you've for sure understood my question comes from a total beginner point of view, hence I consider Lightness Races in Orbit's comment to be the correct answer, since there I found the straightforward answer (...) label = to_string(i); url_full = url_start + label + url_ending; system(url_full.c_str()); – DavideL Feb 03 '19 at 22:23