the hang man has a problem please identify it??
the letters when typed the code shows 'not found'and the same letter has to be typed twice to get it accepted? and the chances to guess the letter decreases how to fix it?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <ctype.h>
#define WORD_COUNT 3
#define MAX_LENGTH 10
typedef char string[MAX_LENGTH];
void main(void) {
string words[WORD_COUNT] = { "bird","fish","lion","ants","bear","deer","fowl" };
char answer[MAX_LENGTH];
char guess;
int count = -0, index, i, found, choice = -7;
char mysteryWord[MAX_LENGTH];
printf("Welcome to Hangman!\n");
printf("\n\nChoose an option\n"
"1) Easy\n"
"2) Moderate\n"
"3) Hard\n"
"Your choice: ");
scanf("%i", &choice); a biref menu case
switch (choice) {
case 1:
count = 5;
break;
case 2:
count = 2;
break;
case 3:
count = 1;
}
srand(time(NULL));
index = rand() % WORD_COUNT;
strcpy(mysteryWord, words[index]);/*actual comparing */
for (i = 0; i < strlen(mysteryWord); i = i + 1)
{
answer[i] = '-';
}
answer[i] = '\0';
printf("%s \n", answer);
while (1 > 0) {
printf("\n %i guess(es) left\n", count);
printf("Guess a letter:");
scanf("%c\n", &guess);
guess = tolower(guess);
found = 0;
for (i = 0; i < strlen(mysteryWord); i++)
{
if (mysteryWord[i] == guess) {
answer[i] = guess;
found = 1;
}
}
if (found == 0) {
printf("Not found!\n");
--count;
}
if (count == 0) {
printf("Game over\n");
printf("The answer is %s.", mysteryWord);
break;
}
else {
what should be here instead of if(answer==mysteryWord) ?
if (strcmp(answer, mysteryWord) == 0)
{
printf("Yes, it's a %s\n", answer);
break; /* or return */
} else
printf("%s", answer);
}
} end of while loop ?
} end of main ?
Change
scanf("%c\n", &guess);
To
scanf(" %c", &guess);
Note the space before %c. The space discards all blanks like newlines and spaces and the %c will then scan the next non-whitespace character.
In your case,when you input data for any scanf,you enter the data and press the enter key.scanf reads the data entered and leaves the \n(newline character) in the stdin. When you scan a character using %c , scanf reads the \n left out by the previous scanf and thus,does not wait for input.
scanf(" %c", &guess);
Please make sure your scanf() is like above with a space before %c
The purpose of space is it gobbles whitespace and special characters
Related
Im making a program where it asks the user to guess a number 1-100 that the computer is thinking about.
In the end of the program, when the user has guessed the correct number, im trying to get the program to ask if user wants to play again (restart the program).
To solve this, i tried using a do while loop & char repeat;. The loop is stretching from almost the beginning of the program, until the end, althought without success. Does anyone know what im doing wrong? Is it because of the function talfunktion, that the loop won't pass?
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int talfunktion (int tal, int guess, int tries, char repeat);
int main () {
do {
srand(time(NULL));
int tal = rand() % 100 + 1; //tal is the correct value that the code is thinking of
int guess; //guess is the guessed value of the user
int tries = 0; // amount of tries it took until getting correct
char repeat;
printf("Psst, the right number is: %d \n", tal); // remove later, not relevant to uppg.
printf("Im thinking of a number between 1 and 100, guess which!");
printf("\nEnter: ");
scanf("%d", &guess);
guess = talfunktion(tal, guess, tries, repeat);
getchar();
getchar();
return 0;
}
int talfunktion(int tal, int guess, int tries, char repeat) {
do {
if (guess < tal) {
tries++;
printf("\nYour guess is too low, try again!");
printf("\nEnter: ");
scanf("%d", &guess);
}
else if (guess > tal) {
tries++;
printf("\nYour guess is too high, try again!");
printf("\nEnter: ");
scanf("%d", &guess);
}
} while (guess > tal || guess < tal);
if (guess == tal) {
printf("\nCongratulations, that is correct!");
tries++;
printf("\nYou made %d attempt(s)", tries);
printf("\nPlay Again? (y/n)");
scanf("%c", &repeat);
}
} while (repeat == 'y' || repeat == 'Y');
}
This is one possible solution
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void talfunktion(int tal, int guess, int* tries)
{
if (guess < tal)
{
(*tries)++;
printf("\nYour guess is too low, try again!");
}
else if (guess > tal)
{
(*tries)++;
printf("\nYour guess is too high, try again!");
}
else if (guess == tal)
{
(*tries)++;
printf("\nCongratulations, that is correct!");
printf("\nYou made %d attempt(s)", *tries);
}
}
int main (void)
{
int tal; //tal is the correct value that the code is thinking of
int guess; //guess is the guessed value of the user
int tries = 0; // amount of tries it took until getting correct
char playAgain;
do {
srand(time(NULL));
tal = rand() % 100 + 1; //tal is the correct value that the code is thinking of
printf("\nIm thinking of a number between 1 and 100, guess which!");
printf("\nEnter: ");
scanf("%d", &guess);
talfunktion(tal, guess, &tries);
printf("\nPsst, the right number is: %d", tal); // remove later, not relevant to uppg.
getchar(); //to halt the code for taking the input
if(guess == tal)
{
tries = 0;
printf("\nPlay Again? (y/n)\n");
scanf("%c", &playAgain);
}
} while (playAgain != 'n');
return 0;
}
There are several things mentioned in the comments that describe problems,
Things you should look at:
Do not define a function inside another function
be careful where you place return statements
when using character testing, use char type for variable
consider simplifying your logical comparisons. (eg guess > tal || guess < tal is the same as guess != tal )
make sure automatic variables are placed such that they are visible where used.
Place space in format specifier: " %c" for scanf() to consume newline character. (instead of excessive use of getchar())
Here is a simplified version of your code, with modified main and talfunktion functions...
char talfunktion(int tal);
int main (void) {
int tal=0;//remove from inside {...} to make it visible to rest of function
char repeat = 'n';
srand(time(NULL));
tal = rand() % 100 + 1; //tal is the correct value that the code is thinking of
do {
repeat = talfunktion(tal);
}while((tolower(repeat) == 'y'));
return 0;
}
char talfunktion(int tal)//do all relevant work in function and return
{ //only what is necessary
int guess = 0;
char repeat = 'n';
printf("Im thinking of a number between 1 and 100, guess which!");
printf("\nEnter a number from 1 to 100: ");
scanf("%d", &guess);
if((guess < 1) || (guess > 100))
{
printf("Entered out of bounds guess...\n");
}
else if (guess != tal)
{
if(guess < tal) printf("guess too small\n");
else printf("guess too large\n");
printf("Try again? <'n' or 'y'>\n");
scanf(" %c", &repeat);//space in format specifier to consume newline character
if(tolower(repeat) != 'y') return 'n';//tolower() allows both upper and lower case
}
else
{
printf("Congratulations: You guessed right.\n");
printf("Play again? <'n' or 'y'>\n");
scanf(" %c", &repeat);
}
return repeat;
}
In the code below I take the input from the user and then I find the digit that was introduced by comparing it to every other digit.
This my code:
#include <stdio.h>
#include <stdlib.h>
int main(){
int i = 0;
int input;
printf("Input a digit: \n");
scanf("%d", &input);
for(; i < 10; i++)
{
if(i == input)
{
printf("Your input is %d\n", i);
break;
}
}
return 0;
}
How do I check for a letter instead? Say the user inputs letter G, and I take that in a loop to compare it to every other character until I find the one it equals to?
You can use pretty much the same code you already have, just scan for a char:
char input;
scanf("%c", &input);
To check the input, use what fits your expectations best. A switch is probably a solid choice:
switch (input) {
case 'G':
printf("G was received\n");
break;
default:
printf("Uninteresting character %c was received\n", input);
}
#include <stdio.h>
int main() {
int i;
while (1) {
printf("Enter no?\n"); // step -1
if (scanf(" %d", &i) > 0) // step-2
printf("Num=%d\n", i);
else
printf("Entered character.Pls enter int\n");
}
}
I want to continue the scan again if user entered a value other than integer when I run the above code with a char input it is running infinite loop. Please suggest why or any solution ...?
#include <stdio.h>
int main() {
int i;
while (1) {
printf("Enter no?\n"); // step -1
if (scanf_s(" %d", &i) > 0) { // step-2
printf("Num=%d\n", i);
break;
}
else {
printf("Entered character.Pls enter int\n");
fseek(stdin, 0, SEEK_END);
}
}
}
If you enter a character say a for the above program it will not match with %d so it will remain in the buffer. The next time in the loop, it will again not match %d and you will enter an infinite loop.
What you can do, is read from the buffer until you encounter a newline character. The second loop will remove any characters until and including the newline character.
#include <stdio.h>
int main() {
int i;
char dummy;
while (1) {
printf("Enter no?\n"); // step -1
scanf(" %d", &i)
if (i > 0) // step-2
printf("Num=%d\n", i);
else
printf("Entered character.Pls enter int\n");
do{
scanf("%c",&dummy);
}while (dummy != '\n'); // Add this loop
}
}
So I'm really confused. I have to write a program in C which is basically an address book, thus I have to get multiple strings from the user (name, ID, phone etc.)
In the beginning I tried using scanf() only but it messed up sometimes with the newline character '\n'. After some googling, I ended up using scanf() for getting single chars or ints (where user answers yes or no questions, or chooses an action from a menu) and fgets() to read the fields of the address book. However, I also had to use fflush(stdin) multiple times after using scanf() which is not recommended here as I have seen. This method worked so far as intended.
So what's the optimal way to read a string from the user? Does fflush(stdin) not offer portability? This is an assignment so I have to think for portability too, since I will execute my code on another computer.
Thank you in advance.
EDIT: So here is what I've got so far. Excuse some words that are written in another language (Albanian). I believe you can understand what's going on.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
void regjistrim();
void kerkim();
void modifikim();
void fshirje();
void rradhitje();
void display();
#define EMRI 50
#define MBIEMRI 50
#define ID 20
#define TEL 20
#define EMAIL 25
typedef struct addressbook
{
char emri[EMRI];
char mbiemri[MBIEMRI];
char id[ID];
char tel[TEL];
char email[EMAIL];
} addressbook;
FILE* Addressbook;
int main(void)
{
char input[2];
int choice;
printf("----------------ADDRESS BOOK----------------");
printf("\n\n\t1 - Regjistrimi i ri\n");
printf("\n\t2 - Kerkim\n");
printf("\n\t3 - Modifikim\n");
printf("\n\t4 - Fshirje\n");
printf("\n\t5 - Rradhitje\n");
printf("\n\t6 - Afishim i address book\n");
printf("\n\t0 - Exit\n");
fgets(input, 2, stdin);
sscanf(input, "%d", &choice);
while (choice < 0 || choice > 6)
{
printf("\nShtypni nje numer nga 0 - 6: \n");
fgets(input, 2, stdin);
sscanf(input, "%d", &choice);
}
switch (choice)
{
case 1:
regjistrim();
break;
case 2:
kerkim();
break;
case 3:
modifikim();
break;
case 4:
fshirje();
break;
case 5:
rradhitje();
break;
case 6:
display();
break;
case 0:
exit(0);
break;
}
return 0;
}
//Regjistron nje qytetar ne addressbook
void regjistrim()
{
char answer;
addressbook entry;
do
{
Addressbook = fopen("Addressbook.txt", "a+");
printf("\nShtypni emrin: ");
fgets(entry.emri, EMRI, stdin);
printf("\nShtypni mbiemrin: ");
fgets(entry.mbiemri, MBIEMRI, stdin);
printf("\nShtypni ID-in: ");
fgets(entry.id, ID, stdin);
printf("\nShtypni nr. telefoni: ");
fgets(entry.tel, TEL, stdin);
printf("\nShtypni email-in: ");
fgets(entry.email, EMAIL, stdin);
fprintf(Addressbook, "Emri: %sMbiemri: %sID: %sNr. telefoni: %sEmail: %s\n", entry.emri, entry.mbiemri, entry.id, entry.tel,entry.email);
fclose(Addressbook);
printf("\nShtypni y/Y neqoftese doni te regjistroni person tjeter: ");
fgets(answer, 1, stdin);
}
while(answer == 'y' || answer == 'Y');
}
With scanf, you can clear the newlines, like that. Also, I have included fgets too.
#include<stdio.h>
int main(void)
{
int i, N = 5;
char buffer[N];
printf("Enter %d characters\n", N+1);
scanf("%5s", buffer); /* MUST check comments below on this page for this! */
/* Clear trailing input */
while(getchar() != '\n')
/* discard */ ;
for(i = 0 ; i < 5 ; ++i)
printf("|%c|\n", buffer[i]);
printf("End with scanf\n\n");
/*****************************************************/
printf("Enter %d characters\n", N+1);
fgets(buffer, 5, stdin);
for(i = 0 ; i < 5 ; ++i)
printf("|%c|\n", buffer[i]);
printf("End with fgets\n\n");
return 0;
}
Also, this code demonstrates the limit you can put to every function for the input.
Source
Well "optimal" is maybe a bit subjective but I found
doing a separate function to read the number makes things
a bit easier and avoid scanf if you don't absolutely need it e.g.
int readNumber(int min, int max)
{
char number[32];
do
{
if ( fgets( number, sizeof(number), stdin ) != NULL )
{
// note that if 'number' is not a number atoi returns 0
int n = atoi(number);
if ( n>= min && n <= max )
{
return n;
}
}
printf( "please enter a valid value between %d and %d\n", min, max );
}
while ( 1 );
return -1; // never reached
}
This is a program I am making for a class. It is supposed to read a letter from a file, and then in the game the user tries do guess the letter. with every wrong attempt the program tells you if the actual letter comes before or after your guess in the alphabet.
For some reason when I run it, the loop skips the first attempt in the getLetter function and does not let you input the letter. Why is this?
#include <stdio.h>
#include <ctype.h>
#define MaxGuesses 5
void instructions();
int playGuess (char solution);
char getLetter ();
int compareLetters (char guess, char solution);
int main()
{
int numGames;
int i;
char solution;
char guess;
int result;
FILE *inFile;
inFile=fopen("inputLet.txt","r");
instructions();
scanf("%d", &numGames);
for(i=1; i<=numGames; i++)
{
printf ("\nThis is game %d\n", i);
fscanf(inFile, " %c", &solution);
result = playGuess(solution);
if (result == 1)
printf("You've WON!\n");
else
printf("You've LOST :(\n");
}
//close file
fclose(inFile);
return 0;
}
void instructions ()
{
printf ("This game consists of guessing letters.\nThe user will have up to 5 chances of guessing correctly,\nupon every failed attempt,\na hint will be provided regarding alphabetical position.\n\nEnter the number of games you wish to play (max 4): ");
}
char getLetter()
{
char userGuess;
printf("\nPlease enter your guess: ");
scanf("%c", &userGuess);
userGuess = tolower(userGuess);
return userGuess;
}
int compareLetters(char guess, char solution)
{
if (guess == solution)
return 1;
else if (guess < solution)
{
printf("\nThe letter that you are trying to guess comes before %c", guess);
return 0;
}
else if (guess > solution)
{
printf("\nThe letter that you are trying to guess comes after %c", guess);
return 0;
}
}
int playGuess (char solution)
{
int numGuesses = 0;
int winOrLose = 0;
char guess;
while(numGuesses < MaxGuesses && winOrLose == 0)
{
guess = getLetter();
winOrLose = compareLetters(guess, solution);
numGuesses++;
}
return winOrLose;
}
It may be consuming a character left in the input buffer (possibly a newline or other whitespace character). You could try changing the format string from "%c" to " %c" as you've done elsewhere, which will skip all the whitespace characters in the buffer before trying to read a character.