Program keeps looping - C++ - c++

The following program does not work properly. It is supposed to be a calculation game which should not loop over and over. I'm not exactly sure what's going on. I tried rearranging some things but that did not help. I noticed that after the user inputs the numbers and answers the question, it just goes to mainMenu even though it should go to display.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
//Declaration Statement
double num1;
double num2;
double answer;
int choice;
void pauseProgram()
{
printf("\nPress any key to continue...");
getchar();
}
//Function Title
void title(char * programTitle)
{
int len = strlen(programTitle);
system("cls");
printf("\n");
for(int i=1; i<40 - len/2;i++) printf(" ");
printf("%s\n",programTitle);
}
void intro()
{
title("Calculation Game");
printf("\nThis program will test your math abilites");
pauseProgram();
}
void userInput()
{
title("Calculation Game");
printf("\nPlease enter positive numbers only\n");
printf("Enter a number:");
scanf("%lf",&num1);
getchar();
printf("Enter another number:");
scanf("%lf",&num2);
getchar();
printf("What is %lf + %lf?",num1,num2);
scanf("%lf",&answer);
if (num1<0 or num2<0)
{
printf("\nSorry, you must enter a positive value! Please try again.");
userInput();
pauseProgram();
}
}
void display()
{
title("Calculation Game");
if (answer=num1+num2)
printf("\nWow you got the right answer\n");
else if (answer!=num1+num2)
printf("\nHmmm...maybe we should review this math concept again!\n");
pauseProgram();
}
void goodbye()
{
title("Calculation Game");
printf("\nFor further information call: 1-800-123-4567\n");
pauseProgram();
}
void mainMenu()
{
title("Calculation Game");
printf("\n1.\tPlay Game");
printf("\n2.\tExit\n");
printf("\nEnter 1 or 2:");
scanf("%d",&choice);
getchar();
if (choice==1)
userInput();
if (choice=2)
goodbye();
if (choice!=1 or choice!=2);
{
printf("\nPlease enter either 1 or 2! Please try again.");
mainMenu();
}
}
//Main program
int main()
{
do
{
intro();
mainMenu();
userInput();
if (answer==num1+num2 or answer!=num1+num2)
{
display();
}
}while(1);
goodbye();
}

As I mentionned in my comment, you can probably see the main() function enters an infinite loop:
do {
...
} while (1)
This loop will not stop until told so. For instance, you can tell the program to exit in your pauseProgram() function :
void pauseProgram()
{
printf("\nPress any key to continue...");
getchar();
exit(0);
}
or in your goodbye() function :
void goodbye()
{
title("Calculation Game");
printf("\nGame designed by David Liubart\n");
printf("\nFor further information call: 1-800-123-4567\n");
pauseProgram();
exit(0);
}
Finally, you could use a break instruction anywhere in the loop in order to exit the loop.

Related

Undefined reference to "operations"

When I compile this program with codeblocks I get undefined reference to "operations". I have only included a part of the program which shows the error. How can I resolve this error?
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
main()
{
---------------------
---------------------
while(1)
{
printf("Choose from one of the following options :\n");
printf("1. XXX\n 2. YYY\n 3. ZZZ\n");
scanf("%d", &choice);
switch(choice)
{
case 1:
case 2:
case 3:
case 4:operations();
return 0;
break;
default: printf("Wrong option choose again\n");
return 1;
}
}
void operations()
{
while(1)
{
printf("Choose from one of the following options :\n");
printf("1. XXX\n2. YYY\n3. ZZZ\n");
scanf("%d",&choice_of_options);
switch(choice_of_options)
{
---------
---------
}
}
}
}
You shouldn't implement operations in your main function:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void operations()
{
while(1)
{
printf("Choose from one of the following options :\n");
printf("1. XXX\n2. YYY\n3. ZZZ\n");
scanf("%d",&choice_of_options);
switch(choice_of_options)
{
---------
---------
}
}
}
int main()
{
---------------------
---------------------
while(1)
{
printf("Choose from one of the following options :\n");
printf("1. XXX\n 2. YYY\n 3. ZZZ\n");
scanf("%d", &choice);
switch(choice)
{
case 1:
case 2:
case 3:
case 4:operations();
return 0;
break;
default: printf("Wrong option choose again\n");
return 1;
}
}
}
If going by message shown , you need to declare a prototype of your function operations before calling it in main .
void operations(void);
int main(void){
...
// then your code

getting keyboard input in c using conio.h

I am trying to learn how to use graphics.h and conio.h libraries.I am developing a graphic program which i need to move a rectangle after keyboard input.ex: if player press right , rectangle should move right side.Problem is i don't know how to get user input.I need to get user input inside a loop continuous.Here is my code.Any help is appreciated(keyword,function name etc)
#include <stdio.h>
#include <conio.h>
#include <graphics.h>
#include <math.h>
void drawrect(int left,int top,int right,int bot);
int main()
{
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\TC\\BGI");
drawrect(5,400,40,450); // default start position
firsttime=1;//counter for if its first time in for loop
int currentl=5;
int currentt=400;
int currentr=40;
int currentb=450;
if(firsttime==1)
{
//get user input and drawrectangle with new inputs
//if player press right add 5 to currentl and current r and
//redraw the rectangle
}
getch();
closegraph();
}
void drawrect(int left,int top,int right,int bot)
{
rectangle(left,top,right,bot);
}
You can use getch() or _getch() to read codes of keys and react on it. But some things you should think over.
1) loop is needed to perform continuois action in your program.
2) keys such as "arrow left", "arrow up", etc. is given by getch() as two codes - the first -32 and the second depends on key.
Use the following programm to see the loop example and to find codes for keys:
#include <stdio.h>
#include <ctype.h>
#include <conio.h>
int main(void)
{
char ch;
printf("Press 'q' to exit prom program\n");
do{
ch = _getch();
printf("%c (%d)\n", ch, ch);
} while( ch != 'q');
}
Its solved this code works thanks for help
#include
#include
void drawrect(int left,int top,int right,int bot);
int main()
{
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\TC\\BGI");
int firsttime=1;//counter for if its first time in for loop
int currentl=5;
int currentt=400;
int currentr=40;
int currentb=450;
char ch;
settextstyle(0, HORIZ_DIR, 1);
outtextxy(20, 20, "To start press 'S'");
ch = getch();
cleardevice();
drawrect(5,400,40,450); // default start position
while(ch!='q')
{
ch = getch();
switch (ch)
{
case KEY_RIGHT:currentr=currentr+5;
currentl=currentl+5;
break;
case KEY_LEFT:currentr=currentr-5;
currentl=currentl-5;
break;
}
cleardevice();
drawrect(currentl,currentt,currentr,currentb);
}
getch();
closegraph();
}
void drawrect(int left,int top,int right,int bot)
{
rectangle(left,top,right,bot);
}

Continuous keyboard input in C

I am creating a console application in C. This is a game in which characters are falling down and user has to press that specific key on the keyboard. I don't know how to detect which key is pressed by the user without pausing the falling characters. When I use scanf the Program waits for input and everything pauses.
Please help me soon!
There is a function called kbhit() or _kbhit it is in the <conio.h> library it returns true or false depending whether a key was hit. So you can go with something like this:
while (1){
if ( _kbhit() )
key_code = _getch();
// do stuff depending on key_code
else
continue;
Also use getch() or _getch which reads a character directly from the console and not from the buffer. You can read more about conio.h functions here they might be very useful for what you want to do.
Note: conio.h is not a standard library and implementations may vary from compiler to compiler.
You may probably look for ncurses
ncurses (new curses) is a programming library that provides an API
which allows the programmer to write text-based user interfaces in a
terminal-independent manner. It is a toolkit for developing "GUI-like"
application software that runs under a terminal emulator.
Also check C/C++: Capture characters from standard input without waiting for enter to be pressed
#include <conio.h>
if (kbhit()!=0) {
cout<<getch()<<endl;
}
I think this might be the non-blocking keyboard input you are looking for.
void simple_keyboard_input() //win32 & conio.h
{
if (kbhit())
{
KB_code = getch();
//cout<<"KB_code = "<<KB_code<<"\n";
switch (KB_code)
{
case KB_ESCAPE:
QuitGame=true;
break;
}//switch
}//if kb
}//void
And as for the characters falling down.. here you go.
Code for if you are on Windows:
/* The Matrix falling numbers */
#include <iostream>
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>
using namespace std;
#define KB_UP 72
#define KB_DOWN 80
#define KB_LEFT 75
#define KB_RIGHT 77
#define KB_ESCAPE 27
#define KB_F8 66
/* Variables*/
char screen_buffer[2000]={' '};
int y_coord[2000]={0};
int x=0, y=0,dy=0;
int XMAX=77;
int YMAX=23;
int KB_code=0;
bool QuitGame=false;
int platformX=35, platformY=23;
/* function prototypes*/
void gotoxy(int x, int y);
void clrscr(void);
void setcolor(WORD color);
void simple_keyboard_input();
void draw_falling_numbers();
void draw_platform();
/* main */
int main(void)
{
/* generate random seed */
srand ( time(NULL) );
/* generate random number*/
for(int i=0;i<XMAX;i++) y_coord[i]= rand() % YMAX;
while(!QuitGame)
{
/* simple keyboard input */
simple_keyboard_input();
/* draw falling numbers */
draw_falling_numbers();
}
/* restore text color */
setcolor(7);
clrscr( );
cout<<" \n";
cout<<" \nPress any key to continue\n";
cin.ignore();
cin.get();
return 0;
}
/* functions */
void draw_falling_numbers()
{
for(x=0;x<=XMAX;x++)
{
/* generate random number */
int MatixNumber=rand() % 2 ;
/* update falling number */
y_coord[x]=y_coord[x]+1;
if (y_coord[x]>YMAX) y_coord[x]=0;
/* draw dark color */
setcolor(2);
gotoxy(x ,y_coord[x]-1); cout<<" "<<MatixNumber<<" ";
/* draw light color */
setcolor(10);
gotoxy(x ,y_coord[x]); cout<<" "<<MatixNumber<<" ";
}
/* wait some milliseconds */
Sleep(50);
//clrscr( );
}
void draw_platform()
{
setcolor(7);
gotoxy(platformX ,platformY);cout<<" ";
gotoxy(platformX ,platformY);cout<<"ÜÜÜÜÜÜ";
setcolor(7);
Sleep(5);
}
void simple_keyboard_input()
{
if (kbhit())
{
KB_code = getch();
//cout<<"KB_code = "<<KB_code<<"\n";
switch (KB_code)
{
case KB_ESCAPE:
QuitGame=true;
break;
case KB_LEFT:
//Do something
platformX=platformX-4;if(platformX<3) platformX=3;
break;
case KB_RIGHT:
//Do something
platformX=platformX+4;if(platformX>74) platformX=74;
break;
case KB_UP:
//Do something
break;
case KB_DOWN:
//Do something
break;
}
}
}
void setcolor(WORD color)
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),color);
return;
}
void gotoxy(int x, int y)
{
static HANDLE hStdout = NULL;
COORD coord;
coord.X = x;
coord.Y = y;
if(!hStdout)
{
hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
}
SetConsoleCursorPosition(hStdout,coord);
}
void clrscr(void)
{
static HANDLE hStdout = NULL;
static CONSOLE_SCREEN_BUFFER_INFO csbi;
const COORD startCoords = {0,0};
DWORD dummy;
if(!hStdout)
{
hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(hStdout,&csbi);
}
FillConsoleOutputCharacter(hStdout,
' ',
csbi.dwSize.X * csbi.dwSize.Y,
startCoords,
&dummy);
gotoxy(0,0);
}

Ncurses does not detect keystroke

I am trying to use ncurses to get non-blocking input.
#include <iostream>
#include <ncurses.h>
int main()
{
char ch;
nodelay(stdscr, TRUE);
while(1)
{
ch= getch();
if (ch == ERR) {
printf("here \n");
usleep(100000);
}
else {
printf("---------------\n");
}
}
}
However when I run this code, irrespective of what I press I always just get "here" printed.
Sample output:
Latitude-E6430:~$ ./try
here
here
here
here
here
here
here
here
here
here
here
here
here
here
here
here
here
here
here
here
here
here
here
dhere
ddhere
dhere
here
The d's and the spaces are not detected at all.
Can someone tell me why?
Thanks.
Finally I found the answer to the question.
I need to do initscr();
After that I am able to print out correctly (the formatting is not-as-expected though).
Correct code:
#include <iostream>
#include <ncurses.h>
int main()
{
char ch;
initscr();
nodelay(stdscr, TRUE);
while(1)
{
ch= getch();
if (ch == ' ') {
// printf("here \n");
usleep(100000);
}
else {
printf("---------------\n");
}
}
}

Wait for input for a certain time

Is there any function that can wait for input until a certain time is reached? I'm making kind of Snake game.
My platform is Windows.
For terminal based games you should take a look at ncurses.
int ch;
nodelay(stdscr, TRUE);
for (;;) {
if ((ch = getch()) == ERR) {
/* user hasn't responded
...
*/
}
else {
/* user has pressed a key ch
...
*/
}
}
Edit:
See also Is ncurses available for windows?
I found a solution using kbhit() function of conio.h as follows :-
int waitSecond =10; /// number of second to wait for user input.
while(1)
{
if(kbhit())
{
char c=getch();
break;
}
sleep(1000); sleep for 1 sec ;
--waitSecond;
if(waitSecond==0) // wait complete.
break;
}
Try with bioskey(), this is an example for that:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <bios.h>
#include <ctype.h>
#define F1_Key 0x3b00
#define F2_Key 0x3c00
int handle_keyevents(){
int key = bioskey(0);
if (isalnum(key & 0xFF)){
printf("'%c' key pressed\n", key);
return 0;
}
switch(key){
case F1_Key:
printf("F1 Key Pressed");
break;
case F2_Key:
printf("F2 Key Pressed");
break;
default:
printf("%#02x\n", key);
break;
}
printf("\n");
return 0;
}
void main(){
int key;
printf("Press F10 key to Quit\n");
while(1){
key = bioskey(1);
if(key > 0){
if(handle_keyevents() < 0)
break;
}
}
}
Based on #birubisht answer I made a function which is a bit cleaner and uses NON-deprecated versions of kbhit() and getch() - ISO C++'s _kbhit() and _getch().
Function takes: number of seconds to wait for user input
Function returns: _ when user does not put any char, otherwise it returns the inputed char.
/**
* Gets: number of seconds to wait for user input
* Returns: '_' if there was no input, otherwise returns the char inputed
**/
char waitForCharInput( int seconds ){
char c = '_'; //default return
while( seconds != 0 ) {
if( _kbhit() ) { //if there is a key in keyboard buffer
c = _getch(); //get the char
break; //we got char! No need to wait anymore...
}
Sleep(1000); //one second sleep
--seconds; //countdown a second
}
return c;
}