Why should the system() function be avoided in C and C++?

There are multiple problems here:

  • First of all, system() as a function is cross-platform and available not just on Windows or Linux. However, the actual programs being called might be platform dependant. For example, you can use system() to create a directory: system("md Temp"). This will only work on Windows, as Linux doesn't know a command called md. For Linux it would have to be system("mkdir Temp"). This goes on, so you'd need a custom solution for each and every platform.
  • This will always spawn a child process that's then executing something. This will in general be slower than some inlined code, e.g. the command or program has to be loaded, has load it's own dependencies, then it has to be executed etc. which is usually a lot more work.

If you're just doing some quick testing on one platform, using system() is perfectly fine, but you shouldn't use it in production environments, unless you really have to. For example, you could allow the user to set an external program that is then executed. For something like this system() is perfectly fine.


There is an answer about system() usage. And there is no standard C++ way to clear console window. For Windows platform you can use such code:

void clear() 
{
    COORD startPos  = { 0, 0 };
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    CONSOLE_SCREEN_BUFFER_INFO screen;
    DWORD written;

    GetConsoleScreenBufferInfo(hConsole, &screen);
    FillConsoleOutputCharacterA(hConsole, ' ', screen.dwSize.X * screen.dwSize.Y, startPos, &written);
    FillConsoleOutputAttribute(hConsole, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE, screen.dwSize.X * screen.dwSize.Y, startPos, &written);
    SetConsoleCursorPosition(hConsole, startPos);
}

And for linux, never tried, but found the way:

#include <curses.h>
erase();