Jump to content

Ciclo que para quando carregarmos numa tecla


Recommended Posts

Posted (edited)

Queria fazer um ciclo que so parasse após carregarmos numa tecla, por exemplo:

while("Qualquer coisa que eu nao sei"){

printf("So para depois de carregarmos numa tecla qualquer");

}

Alguem consegue ajudar?

Edited by roger569
Posted

A função getchar pára até que seja dado um input. Lê bem o link que te forneceram - falaram em getchar ou em kbhit?

You can use kbhit() to check if a key is pressed:

#include <stdio.h>
#include <conio.h> /* getch() and kbhit() */

int main()
{
   char c;

   for(;{
       printf("hello\n");
       if(kbhit()){
           c = getch();
           printf("%c\n", c);
       }
   }
   return 0;
}

Knowledge is free!

Posted

roger569,

Se estiveres a utilizar Windows, a solução reforçada pelo thoga31 é a correcta. Se por acaso o programa precisa de funcionar em Linux, terás que investigar sobre como utilizar as funções tcgetattr e tcsetattr (header <termios.h>), ou então terás que te aventurar com a lib ncurses.

Tudo isto acontece porque o que estás a tentar fazer não diz respeito à linguagem C mas sim ao sistema no qual o programa corre. Por esse motivo, diferentes sistemas têm diferentes formas de aceitar input do utilizador (e diferentes formas de configurarmos esse processo).

  • Vote 1
Posted

como só foram apresentadas as seguintes soluções :

- ou tens o buffered and blocking input reading do scanf

- usa o ncurses ou os conio.h/<termios.h> (dependendo do SO)

eu apresento uma intermédia (código para linux mas fácil de portar ou usar para win32 (dependendo do compilador usado) :

// nao esquecer de linkar a biblioteca "pthread"
//
// exemplo : gcc -o test test.c -lpthread
#include <stdio.h>
#include <stdlib.h>

#include <pthread.h>

#define SECS 3
#define STEP 1

#define RUN 1
#define STOP 0

void * proc(void * data) {
int * run = (int *) data;
int count = 0;

while (*run == RUN) {
	if (count == 0)
		printf("doing stuff for %d seconds ...\n", SECS);

	sleep(STEP);
	count = count >= SECS - STEP ? 0 : count + STEP;
}

pthread_exit(NULL);
}

int main() {
pthread_t thread;
int run = RUN;

printf("starting worker thread ...\n");
pthread_create(&thread, NULL, proc, &run);

printf("waiting for input ...\n");
getchar();

printf("thread signal to stop\n");
run = STOP;

printf("waiting for thread to stop ...\n");
pthread_join(thread, NULL);

return 0;
}

podes testar que o thread auxiliar fica a ser executado enquanto o scanf bloqueia o thread principal.

continuas a ter de carregar esplicitamente na tecla de ENTER, mas como disse, é uma solução intermédia.

IRC : sim, é algo que ainda existe >> #p@p

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.