having problems with the while loop in C - c

this code is not workin for some reason. i tried doing the while loop with stdbool.h lib but that doesn't work. can someone tell me where am i wrong?. i was just trying to make a rock paper game in c in which the right the the rules for winning and when the user has not won i declare it that he has lost. its probably something with loop
#include <stdio.h>
#include <string.h>
void win(){
printf("You win!\n");
}
int main(){
int i =1;
int var=1;
char machine_choice[3];
char ask='\0';
//things that can happen
machine_choice[0]="rock";
machine_choice[1]="paper";
machine_choice[2]="scissor";
srand((unsigned int)time(NULL));
int machine = rand() % 3; //machines actuall choice
char choice[50];
while (i=1) {
printf("what is ur choice. write it in lowercase pls.\n");
scanf("%s", choice);
printf("%s\n", choice);
printf("%s\n", machine_choice[machine]);
if (choice==(machine_choice[machine]))
{
printf("its a tie!\n");
var++;
}
if (choice=="paper" && machine==0)
{
win();
var++;
}
if (choice=="scissor" && machine==1)
{
win();
var++;
}
if (choice=="scissor" && machine==1)
{
win();
var++;
}
if (var==1)
{
printf("do u want to play again(y/n)\n");
scanf(" %c", &ask);
if (ask=='n')
{
printf("okayy!");
break;
}
else
{
var=1;
}
}
}
return 0;
}```

The problem is in the while (i=1) the i always remains equal to 1 so it will never exit that loop, even if you entered an assignment with i = 1 and not a condition. If you wanted to enter a condition you had to enter while(i==1).

Related

My c program keeps crashing and I do not know why

I am writing a program like hangman in c and I am trying to run it .The problem is that it's working fine until I give it a letter to quess the word but then it crashes with -1073741819 (0xC0000005). Can someone help me solve this, I think its something really small that I cant
see . Thank you for helping me!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void Rules(void);
void maskWord (char starword[], int size);
int playRound(char starword[], char answer[]);
void updateStarWord(char starword[], char answer[], char userguess);
int occurancesInWord(char userguess, char answer[]);
int c=0;
char answer[128];
int N;
int main()
{
int ch,size;
char starword[1000];
do
{
printf("---Welcome to Hangman!---\n");
printf("1.Start Game\n2.Instructions\n3.Exit\n");
scanf("%d",&ch);
if(ch>0&& ch<4)
{
switch(ch)
{
case 1:
maskWord(starword,size);break;
case 2:
Rules();break;
}
}
else
system("cls");
}
while(ch!=3);
return 0;
}
void Rules(void)
{
do
{
do
{
printf("\nThe word to guess is represented by a row of dashes representing each letter of the word.");
printf("\nRules may permit or forbid proper nouns, such as names, places, brands, or slang.");
printf("\nIf the guessing player suggests a letter which occurs in the word, the other player writes it in all its correct positions.");
printf("\nIf the suggested letter does not occur in the word, the other player draws one element of a hanged stick figure as a tally mark.\n");
}
while(getchar()!='\n');
}
while(getchar()!='\n');
}
void maskWord (char starword[], int size)
{
printf("Enter word to guess: ");
fflush(stdout);
scanf(" %s", answer);
int N = strlen(answer);
int mask[N];
for (int i=0; i < N; ++i)
{
mask[i] = 0;
}
playRound(mask,N);
}
int playRound(char starword[], char answer[])
{
// Loop over each round of guessing
int gameover = 0;
while (! gameover)
{
// Print word with *s for unguessed letters
printf("The word is : ");
for(int j=0; j < answer; ++j)
{
if (starword[j])
{
printf("%c", answer[j]);
}
else
{
printf("*");
}
}
printf("\n");
// Get player's next guess
char guess;
printf("\nGive a letter: ");
fflush(stdout);
scanf(" %c", &guess);
updateStarWord(starword,answer,guess);
}
}
void updateStarWord(char starword[], char answer[], char userguess)
{
// Mark true all mask positions corresponding to guess
int k;
for(k=0; k < answer; ++k)
{
if ((answer[k]) ==(userguess))
{
starword[k] = 1;
}
}
}
Your for loop doesn't make sense because the condition for terminating it is k < answer. You are comparing an integer (k) to a pointer (answer). The compiler should have warned you about this, so make sure your compiler warnings are turned on and you are paying attention to them. Pointers and integers are different things, and comparing them is almost never what you want to do.
If answer is null-terminated, you could probably replace that condition with answer[k]. Or maybe updateStarWord needs to take an argument that indicates the length of answer, and then the condition would be k < answer_length.

Computer try to guess user number in C

I made a programme to guess user number.
I miss something in my code, but i dont know what.
If i give input b (bigger) or s (lower), its still give me the same result.
Can you tell me please what should i add to Code to work correctly?
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char answer, input;
int untere_grenze=1, upper_limit=999, tipp=0, try1=0;
printf("\n\nThis program tries to guess a number you choose between 1 and 999\n\n");
do
{
try1=0;
do
{
//I think here is my problem
try1+=1;
tipp=untere_grenze+(upper_limit-untere_grenze)/2;
printf("\n%d. try: %d\n", try1, tipp);
upper_limit=tipp-1;
untere_grenze=tipp+1;
//I think here is my problem
do
{
printf("Please enter s (number to be guessed is smaller), b (number to be guessed is larger) or = (guess!):");
scanf(" %c", &input);
input=toupper(input);
} while (input!='S' && input!='B' && input!='=');
} while(input!='=');
printf("\n\nThe computer guessed your number in %d attempts.\n\n", try1);
do
{
printf("Do you want to run the program again (J/N)?\n\n");
scanf(" %c", &answer);
answer=toupper(answer);
} while (answer!='J' && answer!='N');
} while (answer=='J');
return 0;
}
Your code logic is horrible, recommend to rewrite, you can reference mine.
#include <stdio.h>
#include <ctype.h>
#define LOWER_BOUND 1
#define UPPER_BOUND 999
int main (void)
{
int low = LOWER_BOUND, up = UPPER_BOUND, guess, try = 0;
char input;
printf("Program will guess a number between 1 and 999,"
"please input s(smaller), b(bigger), or =(equal)\n");
while (1)
{
if (low <= up)
guess = low + (up - low) / 2;
else {
printf("Program terminate, no more guess value\n");
break;
}
++try;
retry:
printf("guess %d, please input (s/b/=)\n", guess);
scanf(" %c", &input);
if ((input = tolower(input)) == 's') {
up = guess - 1;
} else if (input == 'b')
low = guess + 1;
else if (input == '=')
break;
else
goto retry;
}
printf("Summary: Trial: %d\n", try);
return 0;
}
I don't see your program doing anything with the input.
You should guess lower or higher in the next iteration based on the input.

Read values into an array fails

I want to use a function to scanf up to 10 values for an array with the size 10, and also keep track of the number of values that are in the array because I'll need it later for solving some maths about the array, (max value, min value, etc.).
#include <stdio.h>
int enter(int MeasurmentData[], int nrOfmeasurments)
{
for(int i=0;i<10;++i)
{
int MeasurmentData[10];
scanf("%d",&MeasurmentData[i]);
int nrOfmeasurments = 0;
nrOfmeasurments ++;
return nrOfmeasurments;
}
int main()
{
int MeasurmentData[10];
int nrOfmeasurments;
char menuoption;
while (1)
{
printf("Measurment tool 2.0\n");
printf("v (View)\n");
printf("e (Enter)\n");
printf("c (Compute)\n");
printf("r (Reset)\n");
printf("q (Quit)\n");
printf("enter your option:\n");
scanf(" %c", &menuoption);
if (menuoption =='e') \\ enter values
{
int MeasurmentData[10];
int nrOfmeasurments;
enter(MeasurmentData, nrOfmeasurments);
}
else if(menuoption == 'v') \\\ view values
{
//printf("%d", MeasurmentData[]);
}
else if(menuoption == 'c')
{
}
if(menuoption == 'q')
{
printf("Exiting Measurment tool 2.0\n");
return 0;
}
}
}
When I run the program it should print Measurment tool 2.0, after the the user has the choice of inputting e(enter) which will scan in up to 10 values into an array, if the user clicks q(quit) while in the enter option already he will be returned to the main menu where he can do whatever.
V(view) prints out the array for the user so that he can view what elements are inside.
C(compute) uses the elements inside and the nr of elements to calculate the highest value element, lowest.
There are some errors in your code. Ill try to explain. You have over declared your variables too many times. And since you have a fixed loop you don't need to count the measurements you will always read 10 measurements.
Below are the code with some modifications. Feel free to ask anything about it.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXIMUM_MEASURMENT 10
int enter(int MeasurmentData[])
{
char input[100];
int nrMeasurement = 0;
// reseting Measurment data
for(int i=0;i<MAXIMUM_MEASURMENT;++i) MeasurmentData[i] = 0;
for(int i=0;i<MAXIMUM_MEASURMENT;++i)
{
scanf("%99s", input);
if(strcmp(input, "q") == 0) {
break;
}
MeasurmentData[i] = (int) strtol(input, (char **)NULL, 10);
nrMeasurement++;
}
return nrMeasurement;
}
void showMeasurments(int* MeasurmentData, int length) {
int i = 0;
printf(" ======== Measurment ======== \n");
for(i = 0; i < length; i++) {
printf("%d ", MeasurmentData[i]);
}
printf("\n");
}
int main()
{
int MeasurmentData[MAXIMUM_MEASURMENT];
int nrOfmeasurments;
char menuoption;
while (1)
{
printf("Measurment tool 2.0\n" "v (View)\n" "e (Enter)\n" "c (Compute)\n" "r (Reset)\n" "q (Quit)\n enter your option:\n");
scanf(" %c", &menuoption);
if (menuoption =='e') // enter values
{
enter(MeasurmentData);
}
else if(menuoption == 'v') // view values
{
// show
showMeasurments(MeasurmentData, MAXIMUM_MEASURMENT);
}
else if(menuoption == 'c')
{
}
if(menuoption == 'q')
{
printf("Exiting Measurment tool 2.0\n");
break;
}
}
return 0;
}
Edit: i have updated the code. So i have read the comments of your question and there you have explained a little better what you are trying to accomplish. So since you have the requirement to press 'q' to stop reading values. I have to read all measurments as string and convert to integer if it is not the character q.
Edit 2: Thanks to #user3629249 to point out some of the flaws from the code ill update with his suggestions.

How to print loop result in printf statement in C

I built a letter guessing game and basically the user enters the number of games they want to play, I get a letter from the file, user enters a guess, and i tell them if they are right or not. What i want to do is print "Ready for game #1" after they enter the number of games and also "Getting guess #1" before getting the guess letter. I know its from the loop "i" but i can't seem to figure it out. Here is my code
C
#define _CRT_SECURE_NO_WARNGINGS
#include<stdio.h>
#include<ctype.h>
#define MAXGUESSES 5
//this function provides instructions to the user on how to play the game
void GameRules();
//this function runs one game.
//input: character from the file, void return type
//all other functions to Play one round of a game
//are called from within the GuessTheLetter function
void GuessTheLetter(char);
//this function prompts the player to make a guess and returns that guess
//this function is called from inside the GuessTheLetter( ) function described above
char GetTheGuess();
//this function takes two arguments, the guess from the player
//and the solution letter from the file.
//The function returns 1 if the guess matches the solution and returns a 0 if they do not match
//This function also lets the user know if the guess comes alphabetically before or after the answer
int CompareLetters(char, char);
int main() {
FILE *inPtr;
int numGames, i = 0;
char letter;//letter from file
printf("Welcome to the Letter Guessing Game\n");
GameRules();
printf("How many games? (1 to 8)\n");
scanf("%d", &numGames);
inPtr = fopen("letterList.txt", "r");
for (i = 0; i < numGames; i++) {
fscanf(inPtr, " %c", &letter);
letter = tolower(letter);
GuessTheLetter(letter);
}
return 0;
}
void GuessTheLetter(letter) {
int win = 0;
int numGuesses = 0;
char guess;
while (numGuesses < MAXGUESSES && win == 0) {
guess = GetTheGuess();
guess = tolower(guess);
win = CompareLetters(letter, guess);
numGuesses++;
}
if (win == 1) {
printf("And you Won !!!\n");
}
else {
printf("SORRY, you did not win this round\n");
}
}
char GetTheGuess() {
char guessEntered;
printf("Enter a guess\n");
scanf(" %c", &guessEntered);
return guessEntered;
}
int CompareLetters(letter, guess) {
int winGet;
if (letter == guess) {
printf("The solution and the guess are the same ( %c )", letter);
winGet = 1;
}
else if (letter != guess) {
printf("The solution comes before your guess ( %c )", letter);
winGet = 0;
}
else {
printf("Error!");
}
return winGet;
}
void GameRules() {
printf("First, you will enter the number of games you want to play(1 - 8 games)\n");
printf("For each game you will have 5 chances to guess each letter\n");
printf("Let's begin:\n\n");
}
Is it ok now?
#define _CRT_SECURE_NO_WARNGINGS
#include<stdio.h>
#include<ctype.h>
#define MAXGUESSES 5
//this function provides instructions to the user on how to play the game
void GameRules();
//this function runs one game.
//input: character from the file, void return type
//all other functions to Play one round of a game
//are called from within the GuessTheLetter function
void GuessTheLetter(char);
//this function prompts the player to make a guess and returns that guess
//this function is called from inside the GuessTheLetter( ) function described above
char GetTheGuess();
//this function takes two arguments, the guess from the player
//and the solution letter from the file.
//The function returns 1 if the guess matches the solution and returns a 0 if they do not match
//This function also lets the user know if the guess comes alphabetically before or after the answer
int CompareLetters(char, char);
int main() {
FILE *inPtr;
int numGames, i = 0;
char letter;//letter from file
printf("Welcome to the Letter Guessing Game\n");
GameRules();
printf("How many games? (1 to 8)\n");
scanf("%d", &numGames);
inPtr = fopen("letterList.txt", "r");
for (i = 0; i < numGames; i++) {
printf("Ready to play Game %d\n", i);
fscanf(inPtr, " %c", &letter);
letter = tolower(letter);
GuessTheLetter(letter);
}
return 0;
}
void GuessTheLetter(char letter) {
int win = 0;
int numGuesses = 0;
char guess;
while (numGuesses < MAXGUESSES && win == 0) {
guess = GetTheGuess();
guess = tolower(guess);
win = CompareLetters(letter, guess);
numGuesses++;
}
if (win == 1) {
printf("And you Won !!!\n");
}
else {
printf("SORRY, you did not win this round\n");
}
}
char GetTheGuess() {
char guessEntered;
printf("Enter a guess\n");
scanf(" %c", &guessEntered);
return guessEntered;
}
int CompareLetters(char letter, char guess) {
int winGet;
if (letter == guess) {
printf("The solution and the guess are the same ( %c )\n", letter);
winGet = 1;
}
else if (letter != guess) {
printf("The solution comes before your guess ( %c )\n", letter);
winGet = 0;
}
else {
printf("Error!\n");
}
return winGet;
}
void GameRules() {
printf("First, you will enter the number of games you want to play(1 - 8 games)\n");
printf("For each game you will have 5 chances to guess each letter\n");
printf("Let's begin:\n\n");
}

Returning integer array values from a function in c

I am really struggling on an assignment i have. I have searched the internet and youtube but i am still none the wiser.
The program will have 5 functions in total, but i am stuck on the first. The program should use a 1-D array to read a 4 digit code(must be 4 single digit numbers) entered by the user. My problem arises when i am trying to return that code from the function. All i am getting is the first number. I am aware that you cannot return an array from a function in c and that you have to use pass by reference, this is where i have a problem i do not completely understand how to do this. my code is below along with the output i recieve.
Any help you can give me would be much appreciated, as ive said before i am really struggling.
//program to enter a code and return the code to main
#include <stdio.h>
#include <stdlib.h>
#define CODE 4
//function prototypes
int enter_code(int* code_arr);
main()
{
int code =0;
int option;
int exit1=0;
do
{
//print the menu on screen
printf("\t \t \t1 - Enter the access code\n");
printf("\t \t \t2 - Encrypt code and verify\n");
printf("\t \t \t3 - Exit the program \n");
scanf("%d",& option);
switch(option)
{
case 1:
{
//call enter_code function
code= enter_code(&code);
printf("\n The returned code is %d \n",code);
break;
}
case 2:
{
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 do()
while(exit1!=5 & exit1 <6);
}//end main
int enter_code (int* code_arr)
{
int password[CODE];
int i;
printf("Enter your 4 digit code \n");
for(i=0;i<CODE;i++)
{
scanf("%d",&password[i]);
}
printf("The code entered is:");
for(i=0;i<CODE;i++)
{
printf("%d",password[i]);
}
return(*password); //how do i return the full array
}
Your function can return the code through the array passed as an argument, and use the function return value to indicate an error. You can pass that to another function too. Your simplified code:
#include <stdio.h>
#include <stdlib.h>
#define CODE 4
int enter_code (int* code_arr)
{
int i;
printf("Enter your 4 digit code\n");
for(i=0;i<CODE;i++)
if (scanf("%d", &code_arr[i]) != 1)
return 0;
return 1;
}
int check_code (int* pass_code, int* user_code)
{
int i;
for(i=0;i<CODE;i++)
if (pass_code[i] != user_code[i])
return 0;
return 1;
}
int main(void)
{
int password[CODE] = {0}, passOK[CODE] = {42,24,0,12345678};
if (!enter_code(password))
printf ("Bad password entry\n");
else {
if (check_code(passOK, password))
printf("You unlocked the vault\n");
else
printf("You don't know the passcode\n");
}
return 0;
}
Program output:
Enter your 4 digit code
42
24
0
12345678
You unlocked the vault

Resources