#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
}
}
Related
I started C courses today and teacher assigned to do:
Guess the number and if the number is higher say it is higher but if it is lower say it is lower and count every time you guess AND if you guess it ten times already then say do you want to try again?
I don't know why my code is stop when I just play it only 1 time and how to do the "do you want to play again?"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int x;
char name[20], result;
int count = 0;
int number;
srand(time(NULL));
x = rand() % 100 + 1;
printf("What's your name :");
scanf("%s", &name);
printf("Hello!! %s\n", name);
printf("Guess the number : ");
scanf(" %d", &number);
do {
count++;
if (x > number) {
printf("This is your count : %d\n",count);
printf("The number is higher\n");
} else
if (x < number) {
printf("This is your count : %d\n",count);
printf("The number is lower\n");
} else
if (x == number) {
printf("\nYou're right!!, the number is %d",x);
}
} while (count == 10);
}
The code allows only 1 try because the test while (count == 10) is false at the end of the first iteration. You should have while (count < 10).
You should move the input call scanf(" %d", &number); inside the loop.
Also note that you should break from the loop if the number was found.
For the Do you want to play again? part, you could wrap this code in another loop.
Here is a modified version:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
char name[20] = "", ch;
srand(time(NULL));
printf("What's your name: ");
scanf("%19s", &name);
printf("Hello!! %s\n", name);
for (;;) {
int x = rand() % 100 + 1;
int number;
for (int count = 1; count <= 10; count++) {
printf("Enter your guess: ");
if (scanf(" %d", &number) != 1)
break;
if (x > number) {
printf("This is your count: %d\n",count);
printf("The number is higher\n");
} else
if (x < number) {
printf("This is your count: %d\n",count);
printf("The number is lower\n");
} else
if (x == number) {
printf("You're right!!, the number is %d\n",x);
break;
}
}
printf("Do you want to play again? ");
if (scanf(" %c", &ch) != 1)
break;
if (ch != 'y' && ch != 'Y')
break;
}
return 0;
}
The loop condition in the line
} while (count == 10);
is wrong, because it will be false after the first loop iteration. It would be more meaningful to write
} while (count < 10);
Also, you probably want to put the lines
printf("Guess the number : ");
scanf(" %d", &number);
inside the loop, so that they get executed more than once. Otherwise, you will be processing the same user guess 10 times, which is not what you want.
Another issue is that you don't want the loop to always run 10 times. You only want it to run 10 times if the user hasn't guessed the number. If the user has guessed the number, you want to break out of the loop immediately, without waiting for count to reach 10. For this, you can use the break statement.
I'm a VB guy mostly but can you use while count <= 10?
Perhaps Do Until?
The problem is, basically, that if user enters a:5, b:f, everything works fine. But if it's the other way around and enters a letter to the 'a' variable, the program ends saying "Incorrect input", not letting the user to finish typing in rest of the variables. Why? Is it because of how I dealt with checking if the input is correct in the first place? How to "delay" the message and make it show after user finishes entering variables?
Here's the code:
#include <stdio.h>
int main(void) {
short int l1=0, l2=0, l=0;
int a=0, b=0;
printf("Is number 'a' divisible by number 'b'?\n");
printf("Number a: ");
l1 = scanf("%d", &a);
printf("Number b: ");
l2 = scanf("%d", &b);
l=l1+l2;
if (l<2)
{
printf("Incorrect input");
return 1;
}
else if (b==0)
{
printf("Operation not permitted");
return 1;
}
else if (a%b)
{
printf("%d is not divisible by %d", a, b);
}
else printf("%d is divisible by %d", a, b);
return 0;
}
As Weather Vane already pointed out, the reason the program exits is, that when you enter a character (%c) and the scanf function is waiting for a integer (%d) it ignores the char, doesn't find an int but ends its' search on the '\n' (enter), so your variable l1 stays 0. This happens for all of your scanf calls, as it doesn't clear the buffer from characters that don't match.
Solving this
You can clear the input buffer, so that all the other scanf calls can get an actual input, though, you are still going to get an "Incorrect input" at the end.
printf("Number a: ");
l1 = scanf("%d", &a);
while (getchar() != '\n');
printf("Number b: ");
l2 = scanf("%d", &b);
while (getchar() != '\n');
If you want to repeat the input process until a user enters the numbers correctly, you have to check the return value of the scanf in a while loop, something like this:
do {
printf("Number a: ");
l1 = scanf("%d", &a);
while (getchar() != '\n');
} while (l1 != 1 || l1 != EOF);
Try this:
#include <stdio.h>
int main(void) {
short int l1=0, l2=0, l=0;
int a=0, b=0;
printf("Is number 'a' divisible by number 'b'?\n");
printf("Number a: ");
l1 = scanf("%d", &a);
getchar();
printf("Number b: ");
l2 = scanf("%d", &b);
l=l1+l2;
if (l<2)
{
printf("Incorrect input");
return 1;
}
else if (b==0)
{
printf("Operation not permitted");
return 1;
}
else if (a%b)
{
printf("%d is not divisible by %d", a, b);
}
else printf("%d is divisible by %d", a, b);
return 0;
}
Reference : scanf() leaves the new line char in the buffer
Does anyone know what is the problem with this code? Even after inputting >1 line, the program will end prematurely at the end of the code without allowing the nested while to repeat. Thank you.
#include <stdio.h>
int main() {
int line;
unsigned int sum = 0;
int input;
float average;
printf("Enter number of input lines:");
scanf("%d", & line);
while (line > 0) {
while (input != -1) {
printf("Enter input line:");
scanf("%d", & input);
sum += input;
printf("sum is %d", sum);
printf("Line is %d", line);
}
line--;
printf("Line is %d", line);
}
return 0;
}
In your program the inner loop condition is based on the variable input. But it's value is set as -1 inside the inner loop before exiting the inner loop. But the value of variable input never changes once it becomes -1.
Modify as follows to enter the inner loop on each iteration of the outer loop,
printf("Enter number of input lines:");
scanf("%d",&line);
while (line>0) {
input = 0; /* This line is additional */
while (input != -1) {
printf("Enter input line:");
scanf("%d",&input);
sum += input;
printf("sum is %d",sum);
printf("Line is %d",line);
}
line--;
printf("Line is %d",line);
}
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
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.