En este capítulo del tutorial de C++ veremos como podemos crear un reloj utilizando la librería ctime, la estructura de datos tm y la función Sleep perteneciente a la librería windows.h, en el ejemplo mostraremos en la consola la hora que irá actualizándose cada segundo, también formatearemos los dígitos de la hora, minutos y segundos, para que cada vez que sólo tenga un dígito aparezca el cero al inicio.
reloj.cpp
#include <iostream>
#include <windows.h>
#include <ctime>
#include <sstream>
#include <string>
using namespace std;
void reloj()
{
while (true)
{
time_t now = time(0);
tm * time = localtime(&now);
int hour = time->tm_hour;
int min = time->tm_min;
int sec = time->tm_sec;
ostringstream h;
ostringstream m;
ostringstream s;
h << hour;
m << min;
s << sec;
string horas;
if (h.str().size() == 1) horas = "0" + h.str();
else horas = h.str();
string minutos;
if (m.str().size() == 1) minutos = "0" + m.str();
else minutos = m.str();
string segundos;
if (s.str().size() == 1) segundos = "0" + s.str();
else segundos = s.str();
cout << horas << ":" << minutos << ":" << segundos;
Sleep(1000); //1 segundo
system("cls"); //Limpiar contenido de la consola
}
}
int main(int argc, char *argv[])
{
reloj();
system("PAUSE");
return 0;
}
No hay comentarios:
Publicar un comentario