Counting Dashes to Exit a While Loop in C - c

I made a hangman game using a while loop. I want to use the number of dashes == 0 to break the loop so the player knows that they won. The word is hidden behind "-"s. My word is coding, so it has 6 dashes.
When I run the program, the first guess at the word is an accurate number of dashes. But after the second guess, and so on, it is adding all of the dashes from all the guesses together, not just from that one turn. By the third turn it says I have 9 dashes because that's how many is left over in all of the turns. Any ideas on how to fix?
char word[] = { "Coding" };
char dash[] = {"------"};
char guess;
int numguesses = 10;
int count;
int loopcount;
int i;
int dashcount;
int main()
{
printf("Your Word Is: %s", &dash);
//printf("\nWord: %c", &dash);
loopcount = 10;
count = 1;
while (count <= loopcount)
{
printf("\n\nPick a letter to guess: ");
scanf(" %c", &guess);
printf("\n\nYour Guess Was %c. ", guess);
count = count + 1;
if (guess == 'c')
{
dash[0] = 'c';
printf("\n\n %s", dash);
}
else if (guess == 'o')
{
dash[1] = 'o';
printf("\n\n %s", dash);
}
else if (guess == 'd')
{
dash[2] = 'd';
printf("\n\n %s", dash);
}
else if (guess == 'i')
{
dash[3] = 'i';
printf("\n\n %s", dash);
}
else if (guess == 'n')
{
dash[4] = 'n';
printf("\n\n %s", dash);
}
else if (guess == 'g')
{
dash[5] = 'g';
printf("\n\n %s", dash);
}
else
printf("That Letter Is Not Apart of this Word");
printf("\n\nYou are at Guess Number %d, Your word is at %s", count, dash);
for (i = 0; dash[i]; i++)
{
if (dash[i] == '-')
{
dashcount++;
}
}
printf("\n\nDoes it work ?: %d", dashcount);
}
if (count < numguesses)
{
printf("\n\n\nYou Won the Game, Your Awesome!!");
}
else
{
printf("\n\n\nI'm Sorry, the word was %s.", word);
}
printf("\n\n");
return 0;
}

The issue is that you are not resetting the dashcount variable, so every time it starts with previous value and adds the dashes left
for (i = 0; dash[i]; i++)
{
if (dash[i] == '-')
{
dashcount++;
}
}
You can easily fix this in this way
dashcount=0;
for (i = 0; dash[i]; i++)
{
if (dash[i] == '-')
{
dashcount++;
}
}

Related

How can I search a part of a string and display it?

I have this code here to search a string in a file and display it. How can I edit this piece of code to make it possible to search just a part of this string?
say, the file contains the author "dennis zill", if I search "zill" I want the code to display "dennis zill".
int searchauthor(FILE *ptr) //searching starts
{
int save;
char de;
char in_name[30];
int flag = 1;
save = readbooks();
ptr = fopen("books info.txt", "r");
fflush(stdin);
printf("\n Enter the name of the author: ");
gets(in_name);
printf("-------------------------------------------------");
for(int i = 0; i < save; i++){
if(strcmpi(in_name, info[i].bauthor) == 0){
printf("\n Book name: %s\n Price: %u\n Number of books available: %u\n Number of pages: %u\n-------------------------------------------------", info[i].bname, info[i].price, info[i].numavail, info[i].bpages);
flag = 0;
}
}
if (flag == 1){
printf("\n Not found.\n Do you want to try another search [Y/N]? ");
scanf("%c", &de);
if(de == 'y' || de == 'Y'){
system("cls");
in_name[MAX] = reset(in_name);
fclose(ptr);
return 2;
}
else if(de == 'n' || de == 'N'){
printf("\n You will be redirected to main menu");
for(int k = 1; k <= 5; k++){
Sleep(300);
printf(".");
}
system("cls");
return 1;
}
}
printf("\n\n Do you want to try another search [Y/N]? ");
scanf("%c", &de);
if (de == 'y' || de == 'Y') {
system("cls");
in_name[MAX] = reset(in_name);
return 2; //return 2 to case 3 to search again
}
else if (de == 'n' || de == 'N') {
system("cls");
printf("\n You will be redirected to main menu");
for(int k = 1; k <= 5; k++){
Sleep(300);
printf(".");
}
system("cls");
return 1;
}
} //searching ends
The problem is the line:
if(strcmp(in_name, info[i].bauthor) == 0){
It will succeed only on a full match.
Rather that using strcmp use strstr (or its case-insensitive variant strcasestr() if it's available).
char *strstr(const char *haystack, const char *needle);
The haystack is the full authors name, needle the user's input.
Function returns NULL on failure so it's enough to check if non-NULL was returned.
if(strstr(info[i].bauthor, in_name) != NULL){

Repeat the Program for again Search Array Element

Repeat the Program for again Search Array Element.
#include <stdio.h>
#define MAX_SIZE 100
int main()
{
int arr[MAX_SIZE];
int size, i, toSearch, found;
char repeat;
printf("Enter the size of an array\n");
scanf("%d", &size);
printf("Enter the array elements\n");
for (i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}
do{
printf("\nEnter element to search: ");
scanf("%d", &toSearch);
found = 0;
for(i=0; i<size; i++)
{
if(arr[i] == toSearch)
{
found = 1;
break;
}
}
if(found == 1)
{
printf("\n%d is found at position %d", toSearch, i + 1);
}
else
{
printf("\n%d is not found in the array \n", toSearch);
}
printf("\n \n \nPress Y to again Search Any Element in Array\n \nPress Any other Key to Exit the Program\n\n");
scanf(" %c \t",&repeat);
}
while(repeat == 'y' || repeat == 'Y' );
return 0;
}
I want to repeat my program when user give the input of Y || y otherwise it'll exit the program.
In this code i want to make an array then search the element after this show's the results and in last repeat the code from the search the element block.
I ran your code and everything seems to be working properly except for this line:
scanf(" %c \t",&repeat);
Remove the \t from the scanf and it should work properly. You don't want to scan for a tab character, just the 'Y' or 'y' character.
Also, your use of newlines is a bit unusual. Try putting newline characters at the end of your strings as opposed to the beginning.
Updated code:
#include <stdio.h>
#define MAX_SIZE 100
int main() {
int arr[MAX_SIZE];
int size, i, toSearch, found;
char repeat = ' ';
printf("Enter the size of an array\n");
scanf("%d", &size);
printf("Enter the array elements\n");
for (i = 0; i < size; i++)
scanf("%d", &arr[i]);
do{
printf("Enter element to search: \n");
scanf("%d", &toSearch);
found = 0;
for(i=0; i<size; i++) {
if(arr[i] == toSearch) {
found = 1;
break;
}
}
if(found == 1)
printf("%d is found at position %d\n", toSearch, i + 1);
else printf("%d is not found in the array\n", toSearch);
printf("Press Y to again Search Any Element in Array\nPress Any other Key to Exit the Program\n");
scanf(" %c",&repeat);
}
while(repeat == 'y' || repeat == 'Y' );
return 0;
}
Enclose the block of code you want to repeat in a while loop, something like
bool flag = false;
while(flag==true) {
//Code block
scanf("%c",&input)
if((input == 'y') || (input == 'Y')) {flag = true;}
else {flag = false;}
}
The first method that came to my mind :
#include <stdio.h>
#define MAX_SIZE 100
int main()
{
int arr[MAX_SIZE];
int size, i, toSearch, found;
char repeat;
printf("Enter the size of an array\n");
scanf("%d", &size);
printf("Enter the array elements\n");
for (i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}
do
{
printf("\nEnter element to search: ");
scanf("%d", &toSearch);
found = 0;
for (i = 0; i < size; i++)
{
if (arr[i] == toSearch)
{
found = 1;
break;
}
}
if (found == 1)
{
printf("\n%d is found at position %d", toSearch, i + 1);
}
else
{
printf("\n%d is not found in the array \n", toSearch);
}
printf("\n \n \nPress Y to again Search Any Element in Array\n \nPress Any other Key to Exit the Program\n\n");
repeat = getchar();
repeat = getchar();
if(repeat == 'y' || repeat == 'Y') {
continue;
}
else {
break;
}
} while (1);
return 0;
}

Struggles with TicTacToe

I have written a program in C, that when runs, is supposed to allow the user to play a game of tic tac toe - or noughts and crosses, whether it be against the computer, or another user. I have nearly completed it, and it prints the grid out perfectly fine. However, when I go to input which row/column I want to place the symbol in, instead of inserting the symbol, it just removes a space in the grid, aligning it incorrectly. I have tried to put a loop in the main method which fills the grid in with spaces to try and prevent null values.
If anyone could suggest anything it would be much appreciated. Thanks in advance!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void user_prompt();
void clear_board(char gameBoard[3][3]);
void display_board(char gameboard[3][3]);
void user_move(char gameBoard[3][3]);
void computer_move(char gameBoard[3][3]);
int detect_win(char gameBoard[3][3]);
int gameMode;
char symbol1;
char symbol2;
char nickname1[10];
char nickname2[10] = "TicTacBot";
char gameBoard[3][3];
char playerTurn[10];
int main(void){
int i, j;
char gameBoard [3][3];
clear_board(gameBoard);
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
gameBoard[i][j] = ' ';
}
}
i = 0;
j = 0;
user_prompt();
display_board(gameBoard);
if(gameMode == 2){
for(i = 0; i < 9; i++){
user_move(gameBoard);
display_board(gameBoard);
if(detect_win(gameBoard) == 1){
printf("The winner is %s!!!\n", nickname1);
}
if(detect_win(gameBoard) == 2){
printf("The winner is %s!!!\n", nickname2);
}
}
}
else{
user_move(gameBoard);
display_board(gameBoard);
for(i = 0; i < 4; i++){
printf("TicTacBot's move.\n");
computer_move(gameBoard);
display_board(gameBoard);
if(detect_win(gameBoard) == 1){
printf("The winner is %s!!!\n", nickname1);
}
user_move(gameBoard);
display_board(gameBoard);
if(detect_win(gameBoard) == 1){
printf("The winner is %s!!!\n", nickname2);
}
}
}
if(detect_win(gameBoard) == 0){
("The game ended in stalemate!\n");
}
return 0;
}
/*
Prompts the user to enter a nickname, what symbol they would like to use, and whether they'd rather play against the computer or another user.
*/
void user_prompt(void){
printf("Please choose whether you would rather play against the computer (enter '1'),or another user (enter '2'): \n");
scanf("%d", &gameMode);
getchar();
while(gameMode != 1 && gameMode != 2){
printf("Please enter a valid digit: \n");
scanf("%d", &gameMode);
getchar();
}
if(gameMode == 1){
printf("Please choose whether you would rather play as 'X' (enter 'x') or as 'O' (enter 'o'): \n");
scanf(" %c", &symbol1);
getchar();
if(symbol1 == 'x') {
symbol2 == 'o';
}
else{
symbol2 == 'x';
}
}
else{
printf("Player 1, would you like to play as 'X' (enter 'x') or as 'O' (enter 'o'): \n");
scanf(" %c", &symbol1);
getchar();
while(symbol1 != 'x' && symbol1 != 'o'){
printf("Please enter a valid symbol: \n");
scanf(" %c", &symbol1);
getchar();
}
if(symbol1 == 'x'){
symbol2 == 'o';
}
else{
symbol2 == 'x';
}
}
if(gameMode == 1){
printf("Please enter a nickname: \n");
fgets(nickname1, 10, stdin);
getchar();
}
else{
printf("Please enter a nickname for player 1: \n");
fgets(nickname1, 10, stdin);
getchar();
printf("Please enter a nickname for player 2: \n");
fgets(nickname2, 10, stdin);
getchar();
}
}
/*
Resets the game board.
*/
void clear_board(char gameBoard[3][3]){
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
gameBoard[i][j] = 0;
}
}
}
/*
Displays the game board and all symbols within it.
*/
void display_board(char gameBoard[3][3]){
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
printf(" %c ", gameBoard[i][j]);
if(j == 2){
printf("\n");
}
if(j != 2){
printf("|");
}
}
if(i != 2){
printf("---+---+---\n");
}
}
}
/*
Takes input of a position on the board from the user, then places the user's symbol into that space on the game board.
*/
void user_move(char gameBoard[3][3]){
int row;
int column;
if(playerTurn == nickname1){
printf("Would you like to enter your %c in row 1, 2 or 3? \n", symbol1);
scanf("%d", &row);
getchar();
printf("Would you like to enter your %c in column 1, 2 or 3? \n", symbol1);
scanf("%d", &column);
getchar();
}
else{
printf("Would you like to enter your %c in row 1, 2 or 3? \n", symbol2);
scanf("%d", &row);
getchar();
printf("Would you like to enter your %c in column 1, 2 or 3? \n", symbol2);
scanf("%d", &column);
getchar();
}
if(row < 1 || row > 3){
printf("Please enter a valid row number: \n");
scanf("%d", &row);
getchar();
}
if(column < 1 || column > 3){
printf("Please enter a valid column number: \n");
scanf("%d", &row);
getchar();
}
if(gameBoard[row-1][column-1] != ' '){
printf("The position you entered is already taken. Try again! \n");
display_board(gameBoard);
user_move(gameBoard);
}
else if(gameBoard[row-1][column-1] != ' '){
printf("The position you entered is already taken. Try again! \n");
display_board(gameBoard);
user_move(gameBoard);
}
else{
if(playerTurn == nickname1){
gameBoard[row-1][column-1] = symbol1;
}
else{
gameBoard[row-1][column-1] = symbol2;
}
}
printf("%c", symbol2);
if(gameMode == 2){
return;
}
if(strcmp(playerTurn, nickname1)==0){
strcpy(playerTurn, nickname2);
}
else if(strcmp(playerTurn, nickname2)==0){
strcpy(playerTurn, nickname1);
}
}
/*
Automates a strategic move from the computer, aiming to win the game, or at the least prevent the user from winning
*/
void computer_move(char gameBoard[3][3]){
int row;
int column;
int endTurn = 0;
row = rand() % 3 + 0;
column = rand() % 3 + 0;
if(gameBoard[row][column] != symbol1 && gameBoard[row][column] != symbol2){
gameBoard[row][column] = symbol2;
endTurn = 1;
}
}
/*
Detects a win on the game board. Checks if there are three identical symbols in a row, or if there are no more spaces on the game board.
*/
int detect_win(char gameBoard[3][3]){
for(int row = 0; row < 3; row++){
if(gameBoard[row][0] == gameBoard[row][1] && gameBoard[row][1] == gameBoard[row][2]){
if(gameBoard[row][0] == symbol1){
return 1;
}
if(gameBoard[row][0] == symbol2){
return 2;
}
}
}
for(int column = 0; column < 3; column++){
if(gameBoard[0][column] == gameBoard[1][column] && gameBoard[1][column] == gameBoard[2][column]){
if(gameBoard[0][column] == symbol1){
return 1;
}
if(gameBoard[0][column] == symbol2){
return 2;
}
}
}
if(gameBoard[0][0] == gameBoard[1][1] && gameBoard[1][1] == gameBoard[2][2]){
if(gameBoard[1][1] == symbol1){
return 1;
}
if(gameBoard[1][1] == symbol2){
return 2;
}
}
if(gameBoard[0][2] == gameBoard [1][1] && gameBoard[1][1] == gameBoard[2][0]){
if(gameBoard[1][1] == symbol1){
return 1;
}
if(gameBoard[1][1] == symbol2){
return 2;
}
}
return 0;
}
There's a small logical error:
In line 98, 101, 117, and 121, (and perhaps other places - please check) you have used == (operator for equality check) instead of the = used for assignment.
For example,
symbol2 == 'o';
should be replaced with
symbol2 = 'o';
Hence, it just checks for equality, throws away the result, and continues; with no changes made to symbol2.

C getchar() hangman game

I was given a homework assignment which tasked us with creating a simple hangman game. Below is the code I have. I am currently trying to use if else with getchar() to ask the user to input a lowercase letter and see if it matches one of the letters in the word they are supposed to guess. From my very limited experience the code I have should work and when I step through the program it appears as if it should run properly, but when I actually run the program it seems to skip over the second getchar(). Anyone have any suggestions or help?
#include "stdio.h"
#include "math.h"
int main(void) {
int(a);
int(b);
float(x);
float(c);
float(e);
int word[4] = {116, 101, 115, 116};
int guess[4];
c == 0;
a == 0;
b == 0;
printf("Welcome to Hangman\n");
printf("Input a word--one lower case letter at a time\n");
printf("Enter Guess: ");
x = getchar();
if (x > 122) {
printf(" Error, character must be a lowercase letter");
} else
if (x < 97) {
printf(" Error, character must be a lowercase letter");
} else
if (x == 116) {
printf("t is correct\n");
printf("%d", word[0]);
printf(" _");
printf(" _");
printf(" %d ", word[3]);
e = getchar();
if (e == 101) {
printf("e is correct\n");
printf("%d", word[0]);
printf(" %d", word[1]);
printf(" _");
printf(" %d ", word[3]);
} else
if (e == 115) {
printf("s is correct\n");
printf("%d", word[0]);
printf(" _");
printf(" %d", word[2]);
printf(" %d", word[0]);
} else {
printf(" You guessed wrong");
}
} else
if (x == 101) {
printf("e is correct\n");
printf("_");
printf(" %d", word[1]);
printf(" _");
printf(" _ ");
} else
if (x == 115) {
printf("s is correct\n");
printf("_");
printf(" _");
printf(" %d", word[2]);
printf(" _ ");
} else {
printf(" You guessed wrong");
}
}
When you input a character that you want getchar to read, you end it with the Enter key right? That Enter key will also be put into the input buffer of stdin (which is what getchar reads from) as a newline, '\n'.
That means for each input you give, you actually input two characters.
You need to skip that newline. This can easily be done by just adding a second getchar after the first, like for example
x = getchar();
getchar(); // Read the newline from the Enter key
There is already a good answer, but to clarify the
problem a little bit more, here is a simple piece of code.
The function get_character will return the first entered character
and consume all following characters until the next '\n'.
It is not going to block if one character is EOF.
#include<stdio.h>
int get_character(void);
int main(void)
{
printf("character > ");
int c = get_character();
while(c != EOF && c != 'q')
{
printf("You entered %c\n", c);
printf("character > ");
c = get_character();
}
}
int get_character(void)
{
int c = getchar(), next_c;
if(c == EOF)
{
return EOF;
}
next_c = getchar(); // consume all \n
while(next_c != '\n' && next_c != EOF)
{
fprintf(stderr, "WARNING: consumed non-newline character: 0x%x\n", next_c);
next_c = getchar();
}
return c;
}
By the way: You are able to solve the hangman way faster:
int get_character(void);
#define MAX_TRIALS 3
#define WORD_LEN 4
int main(void)
{
char word[WORD_LEN + 1] = "test";
char correct[WORD_LEN] = {0, 0, 0, 0};
int trials = 0;
while(1)
{
if(trials > MAX_TRIALS)
{
printf("You failed. The word was: %s\n", word);
return 0;
}
printf("character > ");
int c = get_character();
if(c == EOF)
{
printf("bye\n");
return 0;
}
int i, this_char_correct = 0;
for(i = 0; i < WORD_LEN; i++)
{
if(c == word[i])
{
correct[i] = 1;
this_char_correct = 1;
}
if(correct[i])
{
printf("%c", word[i]);
}
else
{
printf("_");
}
}
if(!this_char_correct)
{
trials++;
}
int word_done = 1;
for(i = 0; i < WORD_LEN; i++)
{
word_done &= correct[i];
}
if(! word_done)
{
printf("\nYou have %d trials left\n", WORD_LEN - trials);
}
else
{
printf("\nYou got it.\n");
return 0;
}
}
}
This is just a piece of proof-of-concept code there might be way more elegant ways to solve this.

C simple program

I'm learning starting to learn C, so I tried to make a simple program with what I know. The program SHOULD ask for a letter, ask if you want the position of a letter in the alphabet(if so it displays "x is the y letter in the alphabet" with the suffix) and then it asks if you want the letter in binary and puts it in binary. But for some reason it doesn't work. I tried "manual debugging"(using puts() to see what doesn't work) and the class "getNumber" works but the value changes when it goes to the main class.
a returns "2686719" instead of "a is the 1st letter in the alphabet" and b returns "2b is the 2z\<<y in the alphabet".
This is the code, what did I do wrong?
#include <stdio.h>
#include <stdlib.h>
//011
int main(){
int x = 2;
char letter;
puts("Write a letter");
char temp2;
scanf("%c", &temp2);
int number;
letter = temp2;
puts("get alphabet position? y/n ");
char temp[2];
scanf("%s", temp);
char answer = temp[0];
int tempNumber2 = getNumber(letter);
if(answer == 'y'){
char suffix[3];
int number = tempNumber2;
printf("%d", number);
if (number == 1){
x = 1;
suffix[0] = "s";
suffix[1] = "t";
}else if (number < 27){
suffix[0] = "t";
suffix[1] = "h";
x = 1;
}
if (x == 1){
printf("%c is the %d", letter, number);
printf("%s in the alphabet\n", suffix);
}}else if (answer == 'n'){
x = 1;
}else if (answer != 'y' && answer != 'n'){
puts("ERROR, invalid letter");
x = 3;
};
if(x != 3){
puts("Convert to binary?");
}
return 0;
}
int getNumber(letter){
char tempLetter = letter;
int tempNumber = -1;
char alphabet[27] = "abcdefghijklmnopqrstuvwxyz";
int i = 0;
while(i < 27){
i++;
if(tempLetter == alphabet[i]){
tempNumber = i;
tempNumber++;
printf("%d \n", tempNumber);
return tempNumber;
}
};
}
By the way, I haven't gotten to the binary part hence why it's empty.
As everyone stated in the comments your problem is that suffix's last char is not set to '\0'.
Moreover, you could getNumber in a much simpler way:
int getNumber(char letter) {
return (int)(letter - 'a') + 1;
}
Btw, you can make your code look a little better (didn't change it too much):
int main() {
char letter;
char answer;
puts("Write a letter");
scanf("%c", &letter);
getchar(); // read \n
puts("get alphabet position? y/n ");
scanf("%c", &answer);
getchar(); // read \n
if (answer == 'n') {
return 0;
}
if (answer != 'y') {
puts("ERROR, invalid letter");
return 1;
}
int number = getNumber(letter);
char suffix[3];
suffix[2] = 0;
if (number == 1) {
suffix[0] = 's';
suffix[1] = 't';
} else if (number == 2) {
suffix[0] = 'n';
suffix[1] = 'd';
} else if (number == 3) {
suffix[0] = 'r';
suffix[1] = 'd';
} else {
suffix[0] = 't';
suffix[1] = 'h';
}
printf("%c is the %d%s letter in the alphabet\n", letter, number, suffix);
puts("Convert to binary?");
return 0;
}

Resources