Always running a line/Running 2 lines at once in C - c

Im hoping to make a clicker game from C. I already have the clicking mechanics down and im pretty confident i can do everything else but I can seem to find any articles or help regarding having a running line in the background. For example I have a line of code that allows whenever I click a key i get +1 money, but like most clicker games I want a auto klicker to be running every second or so. So i can just be normally clicking while at the same time theirs a function or line of code that adds +5 money every so often. Ive made my own (delay) code so thats not an issue, its just running a line in the background. Heres what I have so far...
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <time.h>
int main()
{
int menu;
char ch;
int klicks;
int klickses;
klicks=0;
void delay(unsigned int mseconds)
{
clock_t goal = mseconds + clock();
while (goal > clock());
}
printf("Welcome to Key Klicker! This game is a idle game where you slowly gain more and more klicks over time.\n The game is never ending but their are milestones to reach.\n A menu will open up to help navigate through the game.\n");
do{
printf(" 1: Clicking\n 2: Shop\n 3: Exit\n\n");
scanf("%d", &menu);
if(menu == 1)
{
klickses=0;
{
char ch;
printf("Klick as fast as you can! (ESC to exit)\n");
while (1) { //define infinite loop for taking keys
if (kbhit) {
ch = getch(); // Get typed character into ch
klicks=klicks+1;
klickses=klickses+1;
if ((int)ch == 27) //when esc button is pressed, then it will comeout from loop
break;
printf("+1\n");
}
}
}
printf("You have a total of %d klicks!\n", klicks);
printf("You earned %d klicks that session!\n\n", klickses);
}
else if(menu == 2)
{
printf("work in progress\n");
}
else if (menu == 3)
{
printf("exit work in progress\n");
}
}while (1);
}

Hey guys I got it to work! Basically instead of having a auto adder every so seconds I decided to make a stopwatch that starts at the beginning and ends when I go out of the auto clicker. I then minus the end time from the start time and just calculate the auto clicks from their!
I also think with a new variable I just learned called time_t I could make an if statement that if a certain time is passed it would add 5 but anyhoo im not going to vere onto another path. This communities super helpful keep it going!

Related

Creating a grocery list via string inputs and void functions - Input string does not display

I'm fairly new to C (high school student), and my goal is to make a grocery list by inputting a set of characters. Then, the output would print out what I currently added to the list. This would go on forever until I exited the program or went to the main menu.
SCREEN1
00 - GO TO GREETINGS SCREEN
01 - ADD MORE ITEMS TO THE LIST
CODE ENTRY: ___
SCREEN2
Then I entered 01 to add items:
Input "DONE" to end program and see final list.
LIST ENTRY: ______________
SCREEN3
Then I add "apples", then it takes me to this screen:
GROCERY LIST:
POTATOES
FISH
APPLES
After that, it takes me back to SCREEN1, where I would choose whether to go to the greetings screen or add some more.
MY CURRENT CODE:
#include <stdio.h>
#include<stdlib.h>
int main()
{
int n;
char * grocery;
mainMenu:
system("cls");
n = 0;
printf("00 - Go to greetings screen\n01 - Add groceries to list\nENTRY: ");scanf("%d",&n);
if(n == 0)
{
greetings();
goto mainMenu;
}
else if(n == 1)
{
printf("GROCERY ENTRY: ");scanf("%s",grocery);
add(grocery);
goto mainMenu;
}
else
{
printf("Wrong value added. Try again.");
sleep(2);
goto mainMenu;
}
}
void greetings()
{
system("cls");
printf("hello! press any key to go back to menu");
getch();
system("cls");
}
void add(char * a)
{
system("cls");
char listData[1000] = "",slashN[4] = "\n";
strcat(listData,a);
strcat(listData,slashN);
printf("THINGS TO BUY:\n");
puts(listData);
}
NOTES
I used strcat so that it remembers the value of the original string. This'll make sure that the new input will just be put on top of the old data, right? (Hopefully, my logic is correct on that one)
Though, I have not been able to find out whether or not the string data will still be remembered by the program even if I am switching to other menus, such as the Greetings Menu (which is a placeholder for something like a calculator).
Right now, the initial functions work, except for the the grocery list one. Whenever I input a string, nothing comes out of it, even the printf("THINGS TO BUY:") part, leading me to think it's something with what I entered in void add(char * a)
After trying out your code, I received a segmentation fault where you have scanf("%s",grocery);. Try allocating space to the variable, using malloc(3) (see http://man7.org/linux/man-pages/man3/malloc.3.html). For example, char *grocery = (char *)malloc(sizeof(char) * 100); will give you 100 characters to read into your grocery variable from input.
The same objective can also be achieved by simply using char grocery[100]; as you have with other variables.
Furthermore, as many programmers would suggest, try not to use goto(). This can cause spaghetti code (see https://en.wikipedia.org/wiki/Spaghetti_code). Instead, use a while loop that stops only when the user inputs some action designed to stop entering requests.
Lastly, just so you avoid unwarranted results, \n is actually a single character. Therefore, char slashN[4] = "\n" can be char slashN = '\n';.
Happy coding! :D

I am trying to use function admin inside the switch case but it displays error. I am using Visual Studio 2017

How can I make admin function works inside the switch?
I tried doing it but still got an error using Visual Studio 2017
My program is about creating a pharmacy management system that has 2 access as admin and user. Admin can add or update or delete and the user can search or see expiry date.
Error C1075 '': no matching token found
Here is my code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int admin(int1);
int main()
{
char username[50];
int password;
int choice;
int mainmenu = 1;
printf(" \n\n\n\t\t\t\t\tWELCOME TO THE PHARMACY MANAGMENT SYSTEM\t\t\t\t\t");
while (mainmenu == 1) {
printf("\n\n\n\nPlease choose from the current choices\n \n1.ADMIN \n\n2. "
"CUSTOMER\n\n3. EXIT\n\n");
scanf("%d", &choice);
do {
switch (choice) {
case 1:
admin(1);
break;
case 2:
break;
case 3:
printf(
"\n System Closes ...Press Any Key to turn off the system ....");
mainmenu = 0;
break;
}
}
while (choice = 1);
{
printf("\nplease enter your username\t");
scanf("%s", username);
printf("\nplease enter your password\t");
scanf("%d", &password);
if ((strcmp(username, "admin") == 0) && (password == 123123)) {
printf("\n\n\t\t\tYou have logged in succefully....\t\t\n");
break;
} else {
printf("\n\t\tThe username or password is incorrect.\n\t\tPlease "
"verify that CAPS LOCK is not on,and then retype the current "
"username and password.\n\n \a");
}
getch();
return (0);
}
}
You have at least following problems (in decreasing importance):
The final } is missing at the very end of the progran
You havce declared the function int admin(int1) but you havent implemented the function.
int admin(int1) should be declared int admin(int)
the warning for getch is because you forgot to include the conio.h header. This header is Microsoft specific.
Consider also platinum95's answer.
You have some issues with your loops, I think you expect them to do something different.
while (mainmenu == 1)
This loops the program until '3' is entered. This seems fine.
do {
...
}
while (choice = 1);
I think you need to look up how do-while loops work. This loop will never exit, as you assign choice to 1 rather than compare it with 1.
while (choice = 1);
{
...
}
This is not a loop. That while(choice = 1) belongs to the previous do-while loop. You therefore just have a block of code here (which is never executed since the previous loop never exits).
It also seems like the block of code here is intended to be the admin(int) function, (which you didn't include, so I presume this is supposed to be it).
Your best option is to go find a tutorial online of how while and do-while loops work, as well as a tutorial on writing and using functions.

Assignment to write a program that gives the user a choice between two options - C

I have an assignment due and I am drawing a blank on what exactly to do... I'm sure it is simple but I havent quite gotten the hang of things yet. The assignment is -
Write a program that gives the user 2 menu options: either call a function that will print a greeting and your name 4 times or call a function that will count down from 10 to 0 and then print "Blastoff!". Both functions should use for loops to print the appropriate output.
I have the prompt and the functions done so far... but I am unsure of how to display one or the other depending on the choice the user makes. Thank you for your help.
#include <stdio.h>
int main (void){
// declare counter variable
int i;
// prompt the user to make a choice
printf("What would you like to do?\n 1. Print my name\n 2. Count down from 10\n");
printf("\n");
// display greeting and name 4 times
for(i=1;i<=4;i++)
{
printf("Hi, my name is Bridget\n");
}
// display countdown
for(i=10;i>=0;--i)
{
printf("%d\n", i);
}
printf("Blastoff!");
}
You should read the input from user's keyboard:
int c;
c = getchar();
if (c == '1')
{
// display greeting and name 4 times
for(i=1;i<=4;i++)
{
printf("Hi, my name is Bridget\n");
}
}
if (c == '2')
{
// display countdown
for(i=10;i>=0;--i)
{
printf("%d\n", i);
}
}
printf("Blastoff!");
you should use Switch case.
switch(choice) {
case 1: //first for loop
break;
case 2: //second for loop
break;
}
Looks like you are missing a couple of points here. Firstly, you have not yet written any functions. Try looking here to gain some insight on that front.
Secondly, to make a choice based on user input you need to actually get that input somehow. You'll probably want to use scanf.
Lastly, once you have the user's input (say, in a variable declared as int input;) you can use if to control the flow of your program based on that variable like this:
if(input == 1){
greet();
}
else {
countDown();
}
Cheers! If you have any further questions feel free to comment below.
First of all you haven't actually declared you functions. Functions in C should be declared like the main function is. For more info in this see here.
// display greeting and name 4 times
void greeting(){
for(i=1;i<=4;i++)
{
printf("Hi, my name is Bridget\n");
}
}
void countdown() {
// display countdown
for(i=10;i>=0;--i)
{
printf("%d\n", i);
}
printf("Blastoff!");
}
To get the user's input the most common way is by keyboard. scanf accomplishes that in C. Details on scanf here
int main(void){
int i, choice;
//prompt the user to make a choice
// You don't need 2 printf for the newlines stick them to one.
printf("What would you like to do?\n 1. Print my name\n 2. Count down from 10\n\n");
//This takes the user's input and puts it in the variable choice
scanf(%d, &choice);
}
Lastly to decide what to do based on the user input you can use either an if then else statement or a switch. I will provide a solution with an if statement and you can figure the one with the switch on your own. Your final code should look like this.
int main(void){
int i, choice;
//prompt the user to make a choice
// You don't need 2 printf for the newlines stick them to one.
printf("What would you like to do?\n 1. Print my name\n 2. Count down from 10\n\n");
//This takes the user's input and puts it in the variable choice
scanf(%d, &choice);
if(choice == 1){
greeting();
}else{
countdown();
}
}
// display greeting and name 4 times
void greeting(){
for(i=1;i<=4;i++)
{
printf("Hi, my name is Bridget\n");
}
}
void countdown() {
// display countdown
for(i=10;i>=0;--i)
{
printf("%d\n", i);
}
printf("Blastoff!");
}
Bear in mind that this code has a lot of flaws (error checking mainly) but I guess your assigment is not about that.
First of all you need to include libraries with function you will need. You do this by
#include <someLibrary.h>
at the beggining of you document. Libraries mostly have .h extension. Always look for them if you try to do something. You consider them to have best performance and functionality as possible (not always true).
What is next you declare your functions. Function has name, arguments which are going into it, body in which they do something and return value (can be float, int, char etc). If function doesnt return anything, they return void (dont have return at the end). You declare functions before main() with only types of arguments. Whole body is after main (it is better looking).
If you declared function with arguments, you have to provide these arguments to function in () brackets. Even if no arguments are needed, you use them like getch() in example below. Note that function become what it return. If you declared some new variables in function they will be visible only in function. On the other hand function will not see any variable from other function (main too). If you want so, declare global variables (not recommended).
#include <stdio.h>
#include <conio.h> //libraries
void function1(int);
float function2(float); //declaration of functions
int main()
{
char decision;
printf("press 'a' to run function1, press 'b' to run function2\n");
decision=getch(); //first see getch()? look in google for functionality and library !
int someInt=10;
float someFloat=11;
if(decision== 'a')
{
function1(someInt);
}
else if(decision == 'b')
{
printf("%f", funcion2(someFloat)); //example that function become what they return
}
else
{
printf("No decision has been made");
}
getch(); //program will wait for any key press
return 0;
}
void function1(int param1)
{
//print your stuff // this function return void, so doesnt have return; statement
}
float function2(float param1)
{
return 2*param1; //this function have to return some float
}

Re-execute program based on user input in C

Hi i'm trying to learn programming in C on my own and have managed to make a verry, verry simple program that calculates the surface of a circle based on user input.
However the program runs only one time and then closes it.
This was initially the intention because it is only for learning but i want to expand on this program to increase my skills/knowledge and hope someone can point me in the right direction.
What i want to do now is instead of terminating the program after running it once; i would like to offer the user a choise to either stop the program or to continue it and to calculate a new circle.
I understand that it has to be done with an if else statment with the getchar function but i have some issues wrapping my mind around it on how to put it in a program flow. I hope someone can give me some directions on how to tackle this problem or can point me to some documentation that explains this properly.
Currently i have this:
int main(void){
float diameter;
double straal;
double oppervlakte;
char ch;
printf("Type de diameter van de cirkel:\t");
scanf("%g", &diameter);
printf("\n");
straal = diameter / 2;
oppervlakte = PI * (straal * straal);
printf("De straal =\t%g \n\n", straal );
printf("De oppervlakte =\t%f \n\n" , oppervlakte);
printf("Druk enter om af te sluiten.");
scanf("%c",&ch);
getchar();
return 0;
}
and im trying to accomplish something like this(below) but i can't get it to work properly (i get the warning that the label "diameter" is not defined while trying to compile it.)
#include <stdio.h>
#define PI 3.14
int main(void){
float diameter;
double straal;
double oppervlakte;
char ch;
printf("Type de diameter van de cirkel:\t");
scanf("%g", &diameter);
printf("\n");
straal = diameter / 2;
oppervlakte = PI * (straal * straal);
printf("De straal =\t%g \n\n", straal );
printf("De oppervlakte =\t%f \n\n" , oppervlakte);
printf("Druk 'd' om door te gaan of druk enter om af te sluiten.");
if(getchar() == 'd')
{
goto diameter; /* tried to use main(void) here but that also doesnt work */
}
else{
scanf("%c",&ch);
getchar();
}
return 0;
}
i do understand that goto is not the best practise to use but in this case it seemed the easyest way to solve this issue. (and the program is not that complex ofc). However if im wrong in this please let me also know.
Option 1: (likely the best choice): use a do..while loop. Place a do { above your primary code block, and add a } while (<repeat condition>); at the end. The program will run through the code once, check the repeat condition (which will be "did the user enter yes"), and if so repeat, otherwise not.
Option 2: recursively call main(). You said you "tried that", but I'm not sure if you tried it by attempting to use a goto or not. Just use the line main() to call the function again. Note that if you do this too many times you can end up with a stack overflow, because the computer keeps track of each call. It takes a lot to have it be a problem, but with enough repeats it can happen.
You can do something like:
while(true) //this is an endless loop
{
//display a menu like
1. calc area
2. [anything else if you want to add in future]
.
.
.
0. exit
//take user input (e.g 1 for calculating the area)
switch(user input)
{
case 1:
//code to calculate area
break;
case 2:
//code for anything else
break
case 0:
exit(0); //this will terminate the program
}
}
If you follow this pattern, you can add more options to your program in future. You just need to add a case in your switch statement and include that operation in your menu. You can search for menu driven c program to get more details. Try reading about while loop and switch... case statements.
I actually managed to make work in both ways.
Thanks for the tips and suggestions.

program running through my if else after function call

I have a class assignment in C to make a simple calculator that performs three calculations. I haven't completed all of the functions yet but I am having a problem with my calcMenu function. When the function is called the program runs through all of the if else statements and unknown to me, performs only the else statement which is error checking. Than the function is run again which is intended but this time it does not run through all of the if else statements and allows the user to make a choice. I know I have done something really stupid but have been racking my brain for the last hour. If anyone has any pitty for me, than please point me in the right direction. I know all the system calls will Irk some but this is a basic class and our instructor has told us to use them.
Thanks in advance,
Mike
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#define pause system ("pause")
#define cls system ("cls")
//Prototype calculate functions here
void evenOrOdd(int userNumber);
void squareNum(int userNumber);
void cubeNum(int userNumber);
void calcMenu(int userNumber);
void main() {
//Declare local variables here
int userNumber = 0;
printf("\t\t\tThe amazing three function caluculator\n\n\n");
printf("Please enter a whole number that you would like to calculate\n");
scanf("%d", &userNumber);
calcMenu(userNumber);
}
void calcMenu(int userNumber)
{
char calculateOption;
printf("\nWhat calculation would you like to perform with your number?\n\n");
printf("Press A.) to check if your number is even or odd.\n\n");
printf("Press B.) to calculate the square of your number.\n\n");
printf("Press C.) to calculate the cube of your number.\n\n");
printf("press D.) to exit the program.\n");
scanf("%c", &calculateOption);
calculateOption = toupper (calculateOption);
if (calculateOption == 'A')
{
evenOrOdd(userNumber);
}
else if (calculateOption == 'B')
{
squareNum(userNumber);
}
else if (calculateOption == 'C')
{
cubeNum(userNumber);
}
else if (calculateOption == 'D')
{
system("cls");
printf("Thank You for using my amazing calculator.\n\n");
system ("pause");
system ("exit");
}
else
{
printf("Please enter a valid choice");
calcMenu(userNumber);
}
}
void evenOrOdd(int userNumber) {
userNumber = userNumber %2;
if (userNumber == 0)
{
printf("Your number is even. \n");
}
else
{
printf("Your number is odd. \n");
}
}
void squareNum(int userNumber) {
}
void cubeNum(int userNumber){
}
When you read input with scanf you have to press the Enter key to make the program continue. Your scanf call reads the single character from the input, but leaves the Enter key still in the input buffer, to be read next time you call scanf.
There is a very simple trick to solve that: Place a space in the scanf format string before or after the "%c". This will make scanf skip whitespace.
scanf("%c ", &calculateOption);
If you stepped through the code with a debugger you would have easily seen that calculateOption would have been the newline character.
First of all, You can condense all those printf statements into one function to save the extra calls.
Next, you should probably indent your functions, I can't tell where one begins and another ends at a glance.
Third, don't use system("pause"), use getchar().
Fourth, this is optional, you might want to turn those if statements into a switch statement.
Now, on to your question. First of all, instead of using scanf("%c", &calculateOption), just use getchar() here too. In this case, I would write calcMenu() as this:
int calcMenu(int userNumber){
printf("\nWhat calculation would you like to perform with your number?\n\n\
Press A.) to check if your number is even or odd.\n\n\
Press B.) to calculate the square of your number.\n\n\
Press C.) to calculate the cube of your number.\n\n\
Press D.) to exit the program.\n");
switch(toupper(getchar())){
case 'A':
evenOrOdd(userNumber);
break;
case 'B':
squareNum(userNumber);
break;
case 'C':
cubeNum(userNumber);
break;
case 'D':
system("cls"); //this is bad, really.
printf("Thank You for using my amazing calculator.\n\n");
getchar();
return 0;
default:
printf("Please enter a valid choice: ");
calcMenu(userNumber);
break;
}
}
Also, main should always return a value. void main is bad practice.
Disclaimer: The code isn't tested, you shouldn't copy/paste it anyways. I also don't know if you're being forced to use some things or not...

Resources