I'm trying to exit a loop at anytime I want by pressing any key. I've tried the code below but it can't be done. Gotta need your help. Thank you in advance. I'm using a C-Free 5.0.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int b=0, i;
int seconds;
printf("\nEnter number of seconds : ");
scanf("%d", &seconds);
while (b==0)
{
for(i=1;i<=seconds;i++)
{
time_t end = time(0) + 1;
while(time(0) < end)
;
seconds -= 1;
printf("Number of seconds left : %d\n", seconds);
b=kbhit();
}
if(seconds == 0)
{
exit(0);
}
}
printf("Number of remaining seconds left : %d\n", seconds);
}
You are "busy-waiting" in the innermost while loop. That might not be the best solution, but if that is what you want to do, you need to add a test in that loop to check if a key has been hit.
To exit a loop use a function in c++ called khbit. It becomes 1 when any key is pressed and to empty it again assign the key pressed to clear the buffer using getch()
#include <conio.h>
#include <iostream>
using namespace std;
int main()
{
while(1)
{
if(kbhit()) // khbit will become 1 on key entry.
{
break; // will break the loop
}
// Try to use some delay like sleep(100); // sleeps for 10th of second to avoid stress on CPU
}
// If you want to use khbit again then you must clear it by char dump = getch();
// This way you can also take a decision that which key was pressed like
// if(dump == 'A')
//{ cout<<"A was pressed e.t.c";}
}
Related
What am I doing wrong? My code keeps in loop and n goes minus. It was supposed to return 0; at 0.Also whatever I do it starts with 3-2-1-0 even I type "2" it still keeps doing it 3-2-1-0
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
static const char PSWRD[]="1234";
char p[6];
int n=3, y;
printf("Hos geldiniz");
do{
printf("\n\nOgrenci_ID:Elif");
fflush(stdout);
printf("\nSifre:");
scanf("%s", &p);
fflush(stdout);
y=strcmp(p, PSWRD);
if(y==0){
printf("\nGiris Basarili"); `//succesfull login`
return 0;
}else {
printf("Yanlis Sifre, tekrar deneyiniz", 3-n); //wrong password try again
printf("\nKalan hakkiniz ");
printf("%d\n", n);
getchar();
n--;}
if(n<1){
printf("\nHesabiniz bloke oldu");
return 0;
// that means you use all your chance and now you're blocked but my code aint stop here and n goes minus
}
// I am not exactly sure about "3"
//Also what ever i do it starts with 3-2-1-0 even i type "2" it's still keep doing it 3-2-1-0
}while (n<=3);
return 0;
}
while (n<=3);
doesn't agree with
n--;
You seem to want
while (n>0);
Its working for me!
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
int main()
{
static const char PSWRD[]="1234";
char p[6];
int n=3, y;
printf("Welcome");
do{
printf("\n\nStudent_ID:Elif");
fflush(stdout);
printf("\nPassword:");
scanf("%s", p);
fflush(stdout);
y=strcmp(p, PSWRD);
if(y==0){
printf("\nSucessfull Login\n"); //succesfull login
return 0;
}else{
n--;
printf("\nWrong password, try again: "); //wrong password try again
printf("\nRemaining attempts ");
printf("%d\n", n);
getchar();
}
if(n<1){
printf("\nYour account has been blocked\n");
return 0;
}
}while (n>0);
}
When user introduces wrong password, you have more 2 tries and if you enter the password wrong on thats 2 tries program ends! But if you insert it right program makes login, so works fine
In your code, there is no increment of 'n', so the loop keeps going (because n is always smaller than 3). I'm not too sure of what you're trying to do, but you need to change your 'while' condition or statements of 'n' inside the loop.
Currently the loop keeps running forever:
When n=3 - > 3<=3 is true.
When n=2 - > 2<=3 is true.
Etc.
The only way it's going to end is when n decrements until it is equal to the absolute minimum value of an integer which is -2,147,483,648, then it will decrement one more time and change to 2,147,483,647 and the loop will end.
Use printf to watch the value of n, and you will quickly observe that your condition for the do...while loop is incorrect.
However, note the conditional, if(n<=0) with return.
Provide a minimal reproducible example, such as below...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int login(char* PSWRD)
{
int n=3, y;
char p[100+20];
printf("Hos geldiniz");
do{
printf("\nSifre:");
scanf("%100s", p); // limit input size, use p, not &p
if( 0 == strcmp(p, PSWRD) ) {
printf("\nsuccess!");
return 0;
}
printf("Yanlis Sifre, tekrar deneyiniz"); //wrong password try again
n--;
if(n<=0)
{
printf("\nHesabiniz bloke oldu");
return -1;
}
printf("n=%d\n",n); // print current n
} while (n<=3); // this should be (n>0)
return -1;
}
int main()
{
char* PASSWD = "password";
int result;
if( 0 > login(PASSWD) ) {
printf("\nfailed!\n");
exit(1);
}
printf("\nsuccess!\n");
// continue processing here
}
Caveat: Make sure you limit input size to avoid buffer overflow
Read no more than size of string with scanf()
Okay, so I am working on a project right now, and the project is to create a game. Here is the concept below:
Please press any key to begin!
Press the ‘h’ key!
You have 2500 milliseconds to respond!
Press the ‘c’ key!
You have 2400 milliseconds to respond!
Press the ‘k’ key!
You have 2300 milliseconds to respond!
Wrong key! :(
You lose!
You made it through 3 rounds!
Here is the code I have so far:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>
#include <string.h>
/*----------------------------------------------------------------------------
- Prototypes -
-----------------------------------------------------------------------------*/
char random1 ();
int cmpChar(char rand2, char user1);
/*----------------------------------------------------------------------------
- Implementation -
-----------------------------------------------------------------------------*/
int main(int argc, char *argv[])
{
srand(time(NULL)); /* This will ensure a random game each time. */
time_t cdt;
time(&cdt);
ctime(&cdt);
printf("%s\n", ctime(&cdt));
char ans, randChar;
int gameCont = 1;
int score = 0;
printf("This is a Bop-It Game!\n");
printf("\nPress any key to start\n");
getch();
int i = 2600;
while(gameCont == 1){
randChar = random1();
printf("press the '%c' key!\n", randChar);
ans = getch();
gameCont = cmpChar(randChar, ans);
if (gameCont == 1){
score++;
i -= 100;
printf("You have %d milliseconds to respond!\n", i);
}
}
printf("Your score was %d!\n", score);
return 0;
}
char random1 (){
char randInput;
randInput = (rand()%(122-90)+90);
return randInput;
}
int cmpChar(char rand2, char user1){
if (user1 == rand2){
return 1;
}
if (user1 != rand2){
printf("That is incorrect\n");}
else{
return 0;
}
}
If you can see, I implemented a code that kind of mimics the countdown millisecond thing, but it doesnt actually use a timer, it just uses a loop and print statements.
Im on windows OS, and am trying to use #include <sys/time.h> to create a way to implement a timer, and also have it decrease by 100 milliseconds after each iteration.
If you can help with the whole implementation, great, otherwise just a nudge in the right direction would be greatly appreciated.
I'm making a whack-a-mole program, and currently I have the setup for the mole to appear and disappear at random; however, while this is all going on I'll need to accept user input in order to "whack" the mole. Is there any way to do this without pausing the loop to wait for the user to input something, and rather have the loop run WHILE scanning for input? my code is below.
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <stdbool.h>
int main(){
// sets the mole to be initially under_ground
bool above_ground = false;
char mole_presence[1] = {0};
// keeps the mole running as long as the game is in play
while(1){
// while the mole is not above ground, wait until he randomly is
while(above_ground == false){
int r = rand() % 6;
if (r == 5){
printf("a mole has appeared, he's dancing around!\n");
mole_presence[0] = 1;
above_ground = true;
}
else{
printf("%d\n", mole_presence[0]);
sleep(1);
}
}
// while the mole is above ground, he dances until he randomly escapes
while(above_ground == true){
bool escaped = false;
// while he hasn't escaped, continue this loop
while (escaped == false){
int x = rand() % 10;
// if he randomly escapes, break out and show he is no longer above ground
if (x == 5){
printf("he disappeared!\n");
mole_presence[0] = 0;
escaped = true;
}
else{
printf("%d\n", mole_presence[0]);
sleep(1);
}
}
above_ground = false;
}
}
}
I faced the same problem while writing a snake-xenia kind of game. In Windows there is function called _kbhit which can be used to check whether the key is pressed or not. It's prototype is
int _kbhit(void)
Itreturns a nonzero value if a key has been pressed. Otherwise, it returns 0. Read more here : https://msdn.microsoft.com/en-us/library/58w7c94c.aspx
It's not available on linux as there is no conio.h in linux So for linux this answer can help Using kbhit() and getch() on Linux
#include <stdio.h>
void main()
{
int a=1;
char c;
x:for(a=1;a!=0;a++)
{
printf("Hello\n");
c=getch();
if(c=='n')
exit(0);
else
goto x;
}
}
//please assist me with this program by using primary operators only
This is a little different, to show you a simple solution. But if you are not allowed to use kbhit you are stuck.
#include <stdio.h>
#include <conio.h> // include the library header
int main(void) // correct signature for main
{
int c = 0; // note getch() returns `int` type
while(c != 'n') // until correct key is pressed
{
do { // forever
printf("Hello\n");
} while(!kbhit()); // until a key press detected
c = getch(); // fetch that key press
}
return 0;
}
Remember, it only tests for lower-case n.
the posted code does not compile!
The following code will do the job.
Notice that the goto is eliminated
Notice that the unneeded variables are eliminated
Notice that the appropriate header files are included
Notice the signature for the main() function is corrected
#include <stdio.h> // printf()
#include <conio.h> // getch() kbhit() <-- use correct header file
int main( void ) // <-- use valid signature
{
// <-- eliminate unneeded variables
while(1) // <-- non-confusing (and simple) loop statement
{
printf("Hello\n");
if( kbhit() )
{ // then some key has been pressed
if( 'n' == getch() )
{ // then 'n' key has been pressed
break; // <-- exit the loop
}
}
}
} // end function: main
Try this.
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
int main(void) {
char c='y';
while(c!='n') {
while(!kbhit()) {
printf("Hello\n");
}
c=getch();
}
}
Please note that I have not compiled this as conio.h is not available to me right now.
I have a C program, where I just wanted to test if I could reproduce a console spinner used in npm install while it installs a module. This particular spinner simply spins in this order:
|
/
-
\
on the same space, so I use the following program:
#include <stdio.h>
int main() {
char sequence[4] = "|/-\\";
while(1) {
for(int i = 0; i < 4; i++) {
// \b is to make the character print to the same space
printf("\b%c", sequence[i]);
// now I want to delay here ~0.25s
}
}
}
So I found a way to make it rest for that long from <time.h> documentation and made this program:
#include <stdio.h>
#include <time.h>
void sleep(double seconds) {
clock_t then;
then = clock();
while(((double)(clock() - then) / CLOCKS_PER_SEC) < seconds); //do nothing
}
int main() {
char sequence[4] = "|/-\\";
while(1) {
for(int i = 0; i < 4; i++) {
printf("\b%c", sequence[i]);
sleep(0.25);
}
}
}
But now nothing prints to the console. Does anyone know how I can go about producing the behavior I want?
EDIT According to what appears to be popular opinion, I've updated my code above to be the following:
#include <stdio.h>
#include <unistd.h>
int main() {
char sequence[4] = "|/-\\";
while(1) {
for(int i = 0; i < 4; i++) {
printf("\b%c", sequence[i]);
/* fflush(stdout); */
// commented out to show same behavior as program above
usleep(250000); // 250000 microseconds = 0.25 seconds
}
}
}
You will need to flush after you wrote to the console. Otherwise, the program will buffer your output:
fflush(stdout);
Things do get printed to console, it's just does not get flushed. Add fflush(stdout) to see the results, or set the console in an unbuffered mode by calling setbuf:
setbuf(stdout, NULL);
A bigger problem with your code is that your sleep method runs a busy loop, which burns CPU cycles for no good reason. A better alternative would be to call usleep, which takes the number of microseconds:
usleep(25000);
The sleep function isn't really your problem. The issue is that the output is buffered. The simplest thing to do will be to research ncurses.
For now:
fflush(stdout);