Infinite loop till key pressed - c

#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.

Related

My C code aint stop and i can't end the loop

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()

How to scan for input while looping (C Program)

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

error C2447: '{' : missing function header -- Can't resolve this error, what's wrong?

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#include "bcio2.h"
int error, x;
char totalimpulse[80], averageimpulse[80];
void validate_number();
int main(void)
{
clrscr();
do{
printf("\nTotal Impulse delivered: ");
gets(totalimpulse);
validate_number();
} while (error != 0);
printf("You entry %d was valid\n", x);
getch();
return 0;
}
{ //error C2447
clrscr();
do{
printf("\nAverage Impulse delivered: ");
gets(averageimpulse);
validate_number();
} while (error != 0);
printf("You entry %d was valid\n", x);
getch();
return 0;
}
The brackets seen to match and there doesn't seem to be any unnecessary semicolons. I'm assuming this is the correct way to display input/validation. It works fine when run with just the do…while(); loop for totalimpulse but when I copy/paste the exact same between another pair of { } I get just that C2447 error.
The code that starts where the error is is not inside main, or any other function for that matter. If you remove the braces on the error line and the one preceding it, then your second loop will also beside of main. If you want that section to be a different function, you have to include the header for that function. What you put at the top for validate_number is just a promise that you will define that function somewhere (although if you mean for that section at the bottom to be validate_number, I'm pretty sure you don't want it to be recursive).
Right now you just have a block of code, outside any function.
I'm assuming from the rest of your code, that this block of code is supposed to be the definition of void validate_number();, like this:
void validate_number()
{
clrscr();
do{
// ...
return 0;
}
Do note that a void function cannot return a value, so your return 0 should be removed.

How to omit quotation marks usage in char type?

I'm having a really hard time adjusting function to my needs. First of all look at those three files and notice how I have to call f_texture function in main function in order to make it work:
externs.h
#ifndef EXTERNS_H_
#define EXTERNS_H_
extern char t_about[100];
extern int friction;
extern int f_texture(char* ,char*);
#endif
functionA.c
#include <stdio.h>
#include "externs.h"
int main()
{
f_texture("rough","friction");
printf("Friction: %d\n", friction);
f_texture("rough","t_about");
return 0;
}
functionB.c
#include "externs.h"
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
char t_about[100];
int friction;
int f_texture(char* texture,char* what_is_needed)
{
/*Checking if both values are present*/
assert(what_is_needed);
assert(texture);
/*Static array in order to prevent it's disappearance*/
memset(t_about, '\0', sizeof(t_about));
/*Configuring variables for desired texture*/
if (strcmp(texture, "smooth") == 0)
{
strcpy(t_about, "The surface is perfectly smooth, without any "
"protuberances.\n");
friction = 0;
}
else if (strcmp(texture, "rough") == 0)
{
strcpy(t_about, "Rough bumps can be feeled under my fingertips.\n");
friction = 4;
}
/*In case of absent keyword of desired texture it will crash the program*/
else
{
assert(!what_is_needed);
}
/*Returning desired value*/
if (strcmp(what_is_needed, "t_about") == 0)
{
int i=0;
while (t_about[i] != '\0')
{
printf("%c", t_about[i]);
i++;
}
}
else if (strcmp(what_is_needed, "friction") == 0)
{
return friction;
}
/*In case of absent keyword of desired value it will crash the program*/
else
{
assert(!what_is_needed);
}
return 0;
}
And now here is my question: How to rewrite this code to make it possible to call f_texture function without using quotation marks inside? I mean instead of f_texture("abcd","efgh") just to type f_texture(abcd,efgh). I've noticed that this way it's required just after I've wrote this code.
Thanks in advance.
If you don't want to assign string constants to variables or preprocessor object macros, another option is to use preprocessor function macros, using the stringification feature:
#define call_f_texture(a,b) f_texture(#a,#b)
....
call_f_texture(rough,friction);
The C preprocessor will turn this into
f_texture("rough","friction");
You can also use some macros:
#define ROUGH "rough"
#define FRICTION "friction"
#define T_ABOUT "t_about"
int main()
{
f_texture(ROUGH, FRICTION);
printf("Friction: %d\n", friction);
f_texture(ROUGH, T_ABOUT);
return 0;
}
You can do like this,
char rough[]="rough";
char friction[]= "friction";
and call
f_texture(rough, friction);
char a[MAX] = "rouch";
char b[MAX} = "friction";
int main()
{
f_texture();
...
}
int f_texture()
{
/*Checking if both values are present*/
assert(b);
assert(a);
}
or
int f_texture(char* a,char* b)
{
/*Checking if both values are present*/
assert(b);
assert(a);
...
}
int main()
{
char a[MAX] = "rouch";
char b[MAX} = "friction";
f_texture(a,b);
...
}

Exit a loop at anytime

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";}
}

Resources