I can't even figure how to make this work!
So I coded this thing right heere, and in the part where it asks for input, I can't type anything! please hhelp T_T
What I'm making is a Question & Answer time program where a user can only answer the question within the alotted time limit.
Here is my code
#include <stdio.h>
#include "engine.h"
void level2(){
system("cls");
printf("Level 2 \n\n\n");
timer();
if ( time_limit >=0 ) {
printf("BOO");
}
}
int level1() {
char answer;
printf("Hello? \n\n");
scanf("%c",&answer);
time_limit = 20;
timer();
}
int rules() {
time_limit = 15;
system("cls");
printf(" Game Rules \n\n");
printf(" 1. You only have 5 seconds to guess what the correct answer for the question! \n");
}
int credits() {
int menu;
printf(" Coded by : \n");
printf("Lady Dianne Vertucci");
}
int main() {
int menu;
printf("TR \n ");
printf("1. Play \n");
printf("2. Credits \n");
scanf("%d",&menu);
switch (menu) {
case 1:
level1();
break;
case 2:
credits();
break;
default:
printf("Please choose a valid option 'tard");
break;
}
getch();
return 0;
}
This is the engine.h
#ifndef _ENGINE_H_
#define _ENGINE_H_
static int time_limit = 0;
extern int time_limit;
static int score = 0;
extern int score;
int timer() {
while (time_limit !=0)
{
time_limit--;
printf("%02d\r",time_limit);
sleep(1000);
}
}
#endif
In function level1() you should change
scanf("%c",&answer);
to
scanf(" %c",&answer);
^
|
space
This will eat up the newline character \n after entering a char and pressing enter.
Wake up sleepy head
Your call sleep(1000) sleeps for 1000 seconds. Suspect you want sleep(1).
Also recommend #haccks suggestion to use " %c".
Use
flushall(); before scanf
Related
So, I'm totally new to C and I'm having some struggle with some basic concepts, mainly when it is about buffer, memory, and string creation.
So, I have this assignment from College where I need to make an Array of Structs called Vehicles, and during the execution of the program I must take inputs from the user about the Vehicle mark, year, and licensePlate.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Vehicles {
char mark[20];
int modelYear;
char licensePlate[8];
};
int main() {
const int DEFAULT_SIZE = 10;
struct Vehicles vehiclesArr[DEFAULT_SIZE];
for(int i = 0; i < DEFAULT_SIZE ; i++) {
memcpy(vehiclesArr[i].mark, "", 1);
vehiclesArr[i].modelYear = 0;
memcpy(vehiclesArr[i].licensePlate, "", 1);
}
int choice = 0;
int counter = 0;
printf("Hello Professor, my name is Henrique and in this program I will be your guide.\n");
while (choice != 4) {
printf("So, what it will be for today?\n Choose a valid option.\n");
printf("0. Create a new Vehicle.\n");
printf("1. List all saved vehicles.\n");
printf("2. Update a saved vehicle.\n");
printf("3. Delete a saved vehicle.\n");
printf("4. Quit Program.\n");
scanf("%d", &choice);
switch (choice) {
case 0:
if (counter < 10) {
printf("Choose a vehicle mark \n");
scanf("%[^\n]s", vehiclesArr[counter].mark);
printf("\n Choose the model year \n");
scanf("%d", &vehiclesArr[counter].modelYear);
printf("\n Choose license plate \n");
scanf("%[^\n]s", vehiclesArr[counter].licensePlate);
counter++;
break;
} else {
printf("\n Storage limit reached.");
}
case 1:
for(int i = 0; i < DEFAULT_SIZE; i++) {
printf("\nModel: %s", vehiclesArr[i].mark);
printf("\nYear: %d", vehiclesArr[i].modelYear);
printf("\nLicense Plate: %s", vehiclesArr[i].licensePlate);
}
break;
case 2:
break;
case 3:
break;
case 4:
printf("Gently finishing program... Bye Bye!");
break;
default:
printf("\nWhat? The number must be between 0 and 4\n");
}
}
}
The problem is that, when I execute the program and press 0, the program just skip the user input on those two lines bellow:
...
printf("Choose a vehicle mark \n");
scanf("%[^\n]s", vehiclesArr[counter].mark);
...
printf("\n Choose license plate \n");
scanf("%[^\n]s", vehiclesArr[counter].licensePlate);
...
I'm trying to figure out what is happening been a while now, the only thing that works is if I use "%s", but I need the program to handle when user inputs an space character.
Can someone help me, and please explain why is this happening? This is my first question so I would appreciate if you guys also tell me how I can make my questions better.
#include <stdio.h>
#include <string.h>
#define mL 5
#define NL 20
#define UL 6
struct LIST
{
char n[NL];
float am;
char u[UL];
};
struct array
{
struct LIST array;
};
void addCityInformation(struct array *add, int *items);
void printCities(struct array *all, int items);
int main(void)
{
struct array shopping[mL];
int choice, nrOfItemsAdded = 0;
do
{
printf("\nWhat du you want to do?");
printf("\n1 - add grocery");
printf("\n2 - print shopping list");
printf("\n3 - exit");
printf("\nYour choice: ");
scanf("%d", &choice);
while(getchar() != '\n');
switch (choice)
{
case 1:
addCityInformation(&shopping[nrOfItemsAdded], &nrOfItemsAdded);
break;
case 2:
printCities(shopping, nrOfItemsAdded);
break;
case 3:
printf("Exiting program\n\n");
break;
default:
printf("Invalid input\n\n");
break;
}
}
while(choice != 3);
return 0;
}
int clean_stdin()
{
while (getchar()!='\n');
}
void addCityInformation(struct array *add, int *items)
{
if(*items == mL)
printf("No more space in the list\n");
else
{
printf("Enter name: ");
fgets(add->array.n, NL, stdin);
add->array.n[strlen(add->array.n)-1] = '\0';
do {
printf("Enter amount: ");
}while (scanf("%f", &add->array.am )); //loop untill other than float
getchar();
printf("Enter unit: ");
fgets((add->array.u), UL, stdin);
add->array.u[strlen(add->array.u)-1] = '\0';
(*items)++;
}
}
void printCities(struct array *all, int items)
{
printf("\n\n%-20s %-15s %-9s | %-6s\n", "Name", "amount", "unit");
printf("--------------------------------------------------------\n");
for(int i = 0; i < items; i++)
printf("%-20s %-15.1f %-9.4s \n", all[i].array.n, all[i].array.am, all[i].array.u);
}
This is my loop beside that i am only showing a part of the code. It now just continues to give enter amount and letting me register it in the struct. I want to restrict the user to only entering positive numbers and no character at all. And if he types a character it should rerun the loop even if it is 123Av123 it should run the loop and only register the correct number
Edit: now showing the whole code//loop untill other than float is what i want help with
int check=scanf("%f", &add->array.am )
if(check!=1||add->array.am<0){
printf("Incorrect input");
return 1;
}
I think that will do it.
Edit: you wanted it to rerun after so use continue; instead of return;
I have a program in C that the user runs to play a "Guess The Number" game. It runs correctly to start but after the user enters 2 numbers (1 for the initial and 1 for the try again) the program repeats when it is supposed to have a limited number of tries.
Here is my code for the program:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
//----Guess a Number Game.-----------------------------------------
// srand and rand needs the #include <stdlib.h> library
srand(time(NULL)); //seeding the guess a number game with the system time, so the guess a # game always starts at a different point.
int guess;
int correctnum;
correctnum = rand();
printf("Enter a number:");
scanf("%i",&guess);
if(guess>correctnum) // If aa is greater than bb AND aa is greater than cc.
{
printf("Please enter another number, lower this time!");
scanf("%i",&guess);
main();
}
else if (guess<correctnum)
{
printf("Please enter another number, higher this time!");
scanf("%i",&guess);
main();
}
else if (guess==correctnum)
{
printf("You are a WINNER!\n");
printf("You guessed the number right and it was %i!\n",correctnum);
}
int repeat;
printf("Would you like to play again? 1=Yes and 2=No.");
scanf("%i",&repeat);
if(repeat==1)
{
main();
}
if(repeat==2)
{
printf("Hope you had a good time playing the game! See you soon!\n");
return 0;
}
}
Don't call main() recursively. What you need is a simple loop. Something like:
int main(void) {
srand(time(NULL));
int correctnum = rand();
int guess;
int done = 0;
while (! done) {
printf("Enter a number:");
scanf("%i",&guess);
if (guess>correctnum) {
printf("Please enter another number, lower this time!");
} else if (guess<correctnum) {
printf("Please enter another number, higher this time!");
} else /* if (guess==correctnum) */ {
printf("You are a WINNER!\n");
printf("You guessed the number right and it was %i!\n",correctnum);
done = 1;
}
}
}
You should probably check for errors from scanf() too, but first things first.
you can implement all functions you want in a loop:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void main(){
srand(time(NULL));
int guess;
int correctnum;
correctnum = rand() % 100; #it's better to get a number between 1~100
int done = 1;
printf("guess the number:\t");
scanf("%i", &guess);
while(done){
if(guess < correctnum){
printf("Please enter another number, higher this time:\t");
scanf("%i", &guess);
}
else if(guess > correctnum){
printf("Please enter another number, lower this time:\t");
scanf("%i", &guess);
}
else if(guess == correctnum){
printf("well done! if you want to play again, input 1, else input 0:\t");
scanf("%i", &done);
if(done == 1){
correctnum = rand() % 100;
printf("guess the number:\t");
scanf("%i", &guess);
}
}
}
printf("Hope you had a good time playing the game! See you soon!\n");
}
#define _CRT_SECURE_NO_WARNINGS
/*
Purpose: This program allows the user to bet on horses
in a race to earn money on said wagers. I'm trying to run the configureBalance function and then add money to the balance. I'm getting an exception read access violation
*/
#include <stdio.h>
#include <stdlib.h>
#define PAUSE system("pause")
#define CLS system("cls")
#define FLUSH myFlush()
//Prototyping
void getChoice(char *userChoice); // main menu choice
void displayMenu(); // visual menu
void myFlush(); // flush
void configureBalance(int *balance, int *wallet, int *withdraw, int *deposit); // this function is for editing account credentials
void currentBalance(int *balance); // displays the account balance
void coolRaceVisual(); // cool looking visual
//Structs
main() {
int balance = 0, wallet = 0, withdraw = 0, deposit = 0;
char choice = ' ';
do {
getChoice(&choice);
switch (choice) {
case 'A':
configureBalance(balance, wallet, withdraw, deposit);
PAUSE;
break;
case 'B':
coolRaceVisual();
PAUSE;
break;
case 'Q':
CLS;
printf("[][][][][][][][][][][]\n");
printf("[] Goodbye ! []\n");
printf("[][][][][][][][][][][]\n");
break;
default:
printf("[][][][][][][][][][][][][][][][][][][][][][][]\n");//
printf("[] Invalid Selection! Please try again []\n");// This
prompt shows up when the user
printf("[][][][][][][][][][][][][][][][][][][][][][][]\n");//
inputs something incorrectly
PAUSE;
CLS;
break;
return;
}
} while (choice != 'Q');
PAUSE;
}//end main
void getChoice(char *userChoice) {
displayMenu();
scanf("%c", userChoice); FLUSH;
*userChoice = toupper(*userChoice);
}//end getChoice
void displayMenu() {
CLS;
printf(" Horse Derby Ticket Office \n");
printf(" \n");
printf(" A) Configure Balances. \n");
printf(" \n");
printf(" B) Watch the Race. \n");
printf(" \n");
printf(" C) View Race Records. \n");
printf(" \n");
printf(" D) Save and Quit. \n");
printf(" \n");
printf(" Q) Quit. \n");
printf(" \n");
}// end displayMenu
void myFlush() {
while (getchar() != '\n');
}//end myFlush
void configureBalance(int *balance, int *wallet, int *withdraw, int *deposit) {
CLS;
char configureMenuChoice = ' ';
printf("What service would you like? (Not FDIC Insured)\n\n");
printf("A) Add funds to your account balance.\n");
printf("B) Withdraw funds to your wallet.\n");
printf("C) Check Account Balance.\n");
printf("\n\n");
scanf("%c", &configureMenuChoice);
configureMenuChoice = toupper(configureMenuChoice);
Uppercases the choice configuring balances
if (configureMenuChoice == 'A') {
CLS;
printf("How much would you like to add to your account balance? \n");
This adds directly to the balance
scanf("%i", &deposit);
*balance = *balance + *deposit;
}
if (configureMenuChoice == 'C') {
CLS;
currentBalance(*balance); // displays current balance, made a functino so it can be used at will
}
}//end conFigureBalance
void currentBalance(int *balance) {
printf("Your current balance is: %i\n", &balance);
}//end checkBalance
Change this:
scanf("%i", &deposit);
to this:
scanf("%i", deposit);
since deposit is of type int* in that context (the body of the function configureBalance).
It's the same logic as followed here: scanf("%c", userChoice);, so I wonder how you missed it.
My question is i have been asked to write a menu driven program that will ask the user to 1. enter a 4 digit code 2. Encrypt the code and verify against a set 4 digit code. 3. Exit the program. The program should loop back to the start menu after the user is done with their selected option apart from when they choose to exit. i.e the user will enter their code and return to the menu before encrypting and verifying the code entered against a set 4 digit code.
My code below does not loop back to the menu nor does it run correctly when i choose option 1 it asks me to enter the 4 digit code twice. I have tried tiredlessy to fix this but to no avail. Any help you can give me would be great.
#include <stdio.h>
#include <stdlib.h>
#define CODE 4
//prototypes
int enter_code (int* code_arr);
int encrypt_code (int* pass_code, int* user_code);
int main(void)
{
//declare variables
int password[CODE] = {0};
int passOK[CODE] = {4,5,2,3};
int option;
int exit1;
int code;
//do while loop
do
{
//print the menu on screen
printf("\t \t \t \t Pearse Security \n \n");
printf("\t \t \t1 - Enter the access code\n");
printf("\t \t \t2 - Enter the encrypt code and verify\n");
printf("\t \t \t3 - Exit the program \n");
//scan for user input
scanf("%d",& option);
switch(option)
{
case 1:
{
code =enter_code(password);
break;
}
case 2:
{
if (encrypt_code(passOK, password))
printf("You unlocked the vault\n");
break;
}
case 3:
{
// prompt user to a key to exit
printf("\n You choose to exit the program.\n Press a key to exit\n ");
getchar();
exit(0);
break;
}
default:
{
printf("You must enter a number between 1-5\n");
}
} // end switch()
if (!enter_code(password))
{
printf ("Bad password entry\n");
}
else
{
if (encrypt_code(passOK, password))
{
printf("You unlocked the vault\n");
}
else
printf("You don't know the passcode\n");
}
return 0;
}//end do
while(exit1!=4 & exit1 <5);
}//end main()
//enter code function()
int enter_code (int* code_arr)
{
//declare variables for enter_code()
int i;
//prompt user to enter the 4 digit code
printf("Enter your 4 digit code\n");
for(i=0;i<CODE;i++)
{
if (scanf("%d", &code_arr[i]) != 1)
{
return 0;
}//end if()
}//end for()
return 1;
}//end enter_code()
//encrypt code and verify function
int encrypt_code (int* pass_code, int* user_code)
{
//variables for encrypt_code()
int i;
for(i=0;i<CODE;i++)
{
if (pass_code[i] != user_code[i])
{
return 0;
}//end if()
}//end for()
return 1;
}//end encrypt_code()
The output of this program is
Enter 4 digits
4
5
2
3
Enter 4 digits
4
5
2
3
You have unlocked the vault
And the program ends
Why does it ask me to enter the code twice and why does it not loop back to the menu.
I received two compiler warnings about this line
while(exit1!=4 & exit1 <5);
Firstly it should be
while(exit1!=4 && exit1 <5);
It is also undefined behaviour since exit1 has never been assigned a value.
I suggest you replace the line with
while(1);
since case 3: contains an exit().
Next, you say that enter_code() is being called twice. The reason is because it is being called twice: once within case 1: and again outside the switch() code block.
Here is the amended main() in which I deleted the surplus stuff below the switch() block and added a failure message to case 2:
int main(void)
{
int password[CODE] = {0};
int passOK[CODE] = {4,5,2,3};
int option;
int code;
do
{
printf("\t \t \t \t Pearse Security \n \n");
printf("\t \t \t1 - Enter the access code\n");
printf("\t \t \t2 - Enter the encrypt code and verify\n");
printf("\t \t \t3 - Exit the program \n");
scanf("%d",& option);
switch(option)
{
case 1: {
code =enter_code(password);
break;
}
case 2: {
if (encrypt_code(passOK, password))
printf("You unlocked the vault\n");
else
printf("You don't know the passcode\n");
break;
}
case 3:{
// prompt user to a key to exit
printf("\n You choose to exit the program.\n Press a key to exit\n ");
getchar();
exit(0);
break;
}
default: {
printf("You must enter a number between 1-5\n");
}
}
} while(1);
return 0;
}