Paul Alexander Burkart
Paul Alexander Burkart

Reputation: 504

system() function not working C++

I'm currently following a tutorial created by thenewboston on youtube. I'm not following it word for word but close enough.

My simple program:

#include <iostream>
#include <string.h> /* memset */
#include <unistd.h> /* close */
#include <stdio.h>
#include <stdlib.h>
#include <cstdlib>

int main(){
    using namespace std;
    cout << "Those who wander too far off the path of reality. Will be plunged into total Madness." << endl;
    cout << "                                                                                          - BinKill-Ethical" << endl;
    system("cls");
    return 0;

}

This is my first program in C++ that I've created. I know next to nothing but I'm not able to get the system() function to work.

Output: enter image description here

All except for #include <iostream> are suggestions from other stackoverflow posts to try and get this working. None have worked. I'm using G++ to compile, if that matters.

Upvotes: 1

Views: 15524

Answers (2)

AKL
AKL

Reputation: 1389

If you are on Linux, you can use the following instead:

system("clear");

And assuming that you would like to clear the screen before printing, your code becomes like:

#include <iostream>
#include <string.h> /* memset */
#include <unistd.h> /* close */
#include <stdio.h>
#include <stdlib.h>
#include <cstdlib>

int main(){
    using namespace std;
    system("clear");
    cout << "Those who wander too far off the path of reality. Will be plunged into total Madness." << endl;
    cout << "                                                                                          - BinKill-Ethical" << endl;
    return 0;

}

Upvotes: 2

Captain Obvlious
Captain Obvlious

Reputation: 20103

The system function is used to launch an executable that exists on the target platform. On the Windows platforms the cls command is built into the shell and does not exist as a stand-along executable. This makes it impossible to clear the screen using just system("cls") since an executable named "cls" is not a standard part of Windows. You can still clear the screen on a default installation of Windows but you have to do it by launching the command shell.

system("cmd /c cls");

The /c option instructs the shell (cmd) to execute the command cls and then exit.

If you are writing your program specifically for Windows I suggest taking a look at the console API. If you are writing your application for multiple platforms I suggest taking a look at ncurses. Both will allow you to clear the screen in a more programmatic approach instead of using just system.

Upvotes: 1

Related Questions