martes, 1 de febrero de 2011

How to implement a getchar or getch function using C++ libraries.

There is no getchar() function in C++ as it's not in iostream.h library. We can implement a getchar() function using some bash commands to implement the function under GNU/Linux. In Windows you can import the library conio.h so you don't have this problem.

Here is a sample code of getch() or getchar() function development:

For example, we create a file named nstdio.h which contains the function getch().


#include <iostream> #include <string> #include <sstream> #include <fstream> #include <cstdlib> using namespace std; static bool isGenerated = false; const string readCharScript[7] = {"#!/bin/sh" , "tput smso", "tput rmso", "oldstty=`stty -g`", "stty -icanon min 1 time 0", "dd bs=1 count=1 of=output >/dev/null 2>&1", "stty \"$oldstty\"" }; void resetOutputFile() { ofstream outputFile( "output", fstream::out ); outputFile << "$"; outputFile.close(); } void GenereFile() { resetOutputFile(); ofstream readFile( ".readone", fstream::out ); for ( int i = 0; i < 7; i++ ) readFile << readCharScript[i] << endl; readFile.close(); system("chmod ugo+x .readone"); isGenerated = true; } char getch() { if (!isGenerated) GenereFile(); system("./.readone"); const int EOL = '$'; char ch; ifstream file("output", fstream::in); while (ch == EOL) file >> ch; file.close(); resetOutputFile(); return ch; }

A file to test the getch() function called test.cpp.


#include <iostream> #include "nstdio.h" using namespace std; int main() { char ch = getch(); if (ch == '\n') cout << "Se pulsó intro" << endl; else cout << endl << "El caracter es: " << ch << endl; return 0; }



As you can see I didn't use objects, but you can encapsulate the methods in a class. The important thing is that I only use C++ libraries.

Furthermore, don't forget that C++ is a multiparadigm language, so you can use both, OO and procedural programming.

Have a nice programming!

No hay comentarios:

Publicar un comentario

Escriba su comentario (no necesita registrarse).