Alternative clrscr()
in C++
The clrscr()
function, often found in older C++ code, is a non-standard function used to clear the console screen. It's not part of the standard C++ library and its availability depends on the compiler and operating system.
Here are some alternatives to clrscr()
in C++ that are more portable and reliable:
Using system commands:
The most straightforward approach is to use system commands, which are platform-specific:
Windows:
#include
#include
using namespace std;
int main() {
system("cls"); // Clears the console screen on Windows
cout << "Screen Cleared!" << endl;
return 0;
}
Linux/macOS:
#include
#include
using namespace std;
int main() {
system("clear"); // Clears the console screen on Linux/macOS
cout << "Screen Cleared!" << endl;
return 0;
}
Using cout
manipulations:
Another approach is to manipulate the cout
stream to achieve the desired effect:
#include
#include
using namespace std;
int main() {
// Clear the console by printing a large number of newlines
cout << setfill('\n') << setw(100) << "";
cout << "Screen Cleared!" << endl;
return 0;
}
This method prints a large number of newline characters, effectively pushing the previous output off the screen.
Using libraries:
You can also use external libraries like ncurses to have more control over console output, including screen clearing:
#include
#include
using namespace std;
int main() {
initscr(); // Initialize ncurses
clear(); // Clear the screen
refresh(); // Update the screen
cout << "Screen Cleared!" << endl;
endwin(); // Terminate ncurses
return 0;
}
Important: Remember to link the ncurses library when compiling your program.
Considerations:
- Portability: Using system commands ensures portability across different platforms, but you need to handle platform-specific calls.
- Efficiency: The
cout
manipulation method might not be as efficient as system commands or libraries. - Control: Using libraries like ncurses gives you finer control over console output and interactions.
Ultimately, the best alternative for you will depend on your specific needs and preferences. Choose the method that best suits your project and coding style.