This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 9 months ago.
#include <stdio.h>
void print_instructions(){
printf("You will need to input a letter to guess,\n");
printf("Then let the player see the screen, and make guesses.\n");
}
int main(){
char input;
print_instructions();
printf("What letter will the player guess? ");
scanf("%c", &input);
printf("The letter is '%c' (ascii %d)\n", input, input);
int asterisk = 1;
while(asterisk <= 10){
printf("*\n");
asterisk++;
}
int attemptNum = 1;
int z;
while(attemptNum <= 10){
char guess;
printf("What is guess #%d? ", attemptNum);
scanf("%c", &guess);
if(guess <= 96){
printf("Your guess must be a valid letter!\n");
}
else if(guess < input){
printf("Not quite! Guess later in the alphabet.\n");
}
else if(guess > input){
printf("Not quite! Guess later in the alphabet.\n");
}
else{
printf("Congratulations! You got the letter right!\n");\
break;
}
attemptNum++;
}
}
I think I did nothing wrong using while, but I keep having an error like this:
What did I do wrong?
I have no idea why while repeats itself twice on the odd numbers. Is it something to do with the data structure?
There is no issue with while, but with your scanf - it's reading enter from the buffer that you confirmed input with. try scanning like this to clear the enter
scanf("%c\n", &guess);
Because every time you press the enter button on the keyboard, the enter itself will be also seen as a character \n. Its ASCII code is 10, which is invalid for your condition if(guess<=96). Your problem isn't related with the while loop at all.
To solve this problem:
Use getchar() to "absorb" \n
Use fflush(stdin) to clear all characters remained
Related
This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 2 years ago.
This code is meant to ask for an integer input from the user, then confirm if it is the input, and then display whether it is positive or negative if the answer is 'yes'.
#include<stdio.h>
int main()
{
int s;
printf("Enter an integer:");
scanf("%d", &s);
printf("So, you entered %d\n", s);
printf("Is that correct? (y/n)\n");
char chr;
scanf("%c", &chr);
if(chr=='y')
{
if (s<0)
{
printf("\n%d is a negative number.\n", s);
}
else if(s==0)
{
printf("\nThe number which you entered is Zero\n");
}
else
{
printf("\n%d is a positive number\n", s);
}
}
else if(chr=='n')
{
printf("\nSorry, for that. Please re-execute this program.\n");
}
else
{
printf("\nEnter the write keyword! Re-execute this program.\n");
}
return 0;
}
But this doesn't ask for any input during the char scanf.
Syntax error, or something else?
It's reading the line feed (ASCII 10) produced when you pressed ENTER. You could use
scanf(" %c", &chr);
The space causes whitespace (including LF) to be skipped.
I have written this simple program, which is supposed to calculate the factorial of a number entered by the user. The program should ask the user to stop or continue the program in order to find the factorial of a new number.
since most of the time user don't pay attention to CapsLock the program should accept Y or y as an answer for yes. But every time I run this program and even though I enter Y/y , it gets terminated !
I googled and found out the problem could be due to new linecharacter getting accepted with my character input so, I modified the scanf code from scanf("%c", &choice); to scanf("%c ", &choice); in order to accommodate the new line character , but my program is still getting terminated after accepting Y/y as input.
Here is the code . Please if possible let me know the best practices and methods to deal with these kinds of issues along with the required correction.
#include<stdio.h>
#include"Disablewarning.h" // header file to disable s_secure warning in visual studio contains #pragma warning (disable : 4996)
void main() {
int factorial=1;//Stores the factorial value
int i; //Counter
char choice;//stores user choice to continue or terminte the program
do {//Makes sure the loop isn't terminated until the user decides
do{
printf("Enter the no whose factorial you want to calculate:\t");
scanf("%d", &i);
} while (i<0);
if (i == 0) //calculates 0!
factorial = 1;
else {//Calculates factorial for No greater than 1;
while (i > 0) {
factorial = factorial*i;
i--;
}
}
printf("\nThe factorialof entered no is :\t%d", factorial);//prints the final result
printf("\nDo you want to continue (Y/N)?");
scanf("%c ", &choice);
} while (choice =="y" || choice =="Y"); // Checks if user wants to continue
}
I'm a beginner in programming and I'm running this code in visual studio 2015.
Just modify your scanf like following:
printf("\nDo you want to continue (Y/N)? ");
scanf(" %c", &choice); //You should add the space before %c, not after
also you should use:
} while (choice == 'y' || choice == 'Y'); // Checks if user wants to continue
NOTE:
Simple quote ' is used for characters and double quote " is used for string
Your second-last line has a string literal "y", which should be a character literal i.e. 'y':
} while (choice =="y" || choice =="Y");
This should be:
} while (choice =='y' || choice =='Y');
Also, your scanf() doesn't consume whitespace. Add a space before %c to make it ignore newlines or other spaces:
scanf(" %c", &choice);
Try doing the following even after the correction there are still some bugs in the code
In your code if you type 'Y' and recalculate a factorial it gives wrong answer as
int factorial is already loaded with the previous value
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
using namespace System;
using namespace std;
int calculateFactorial(int i);
int main()
{
int i;
char choice;
do{
printf("Enter the no whose factorial you want to calculate:\t");
scanf("%d", &i);
printf("\n The factorial of entered no is :\t %d", calculateFactorial(i));
printf("\n Do you want to continue (Y/N)?");
scanf(" %c", &choice);
} while (choice == 'y' || choice == 'Y');
return 0;
}
int calculateFactorial(int i) {
int factorial = 1;
if (i == 0){
factorial = 1;
}else {
while (i > 0){
factorial = factorial*i;
i--;
}
}
return factorial;
}
I am rewriting the Guessing Game code from 'C Programming for Absoulute Beginners' to verify that the user has entered in a digit, using the isdigit() function.
The rest of the code works, in terms of error checking; but the moment that the user enters in a non-digit, the code goes into an infinite loop.
#include <stdio.h>
#include <stdlib.h>
#define NO 2
#define YES 1
main()
{
int guessGame;
guessGame = 0;
int iRandomNum = 0;
int iResponse = 0;
printf("\n\nWould you like to play \"The Guessing Game\"?\n\n");
printf("\nType '1' for Yes or '2' for No!\n\n");
scanf("%d", &guessGame);
do{
if(guessGame == YES){
iRandomNum = (rand() % 10) + 1;
printf("\nGuess a number between 1 and 10:\n\n ");
scanf("%d", &iResponse);
if(!isdigit(iResponse)){
printf("\nThank you\n");
printf("\nYou entered %d\n", iResponse);
if(iResponse == iRandomNum){
printf("\nYou guessed right\n");
printf("\nThe correct guess is %d!\n", iRandomNum);
printf("\nDo you wish to continue? \n");
printf("\nType '1' for Yes or '2' for No!\n\n");
scanf("%d", &guessGame);
} else {
printf("\n\nSorry, you guessed wrong\n");
printf("\nThe correct guess was %d!\n", iRandomNum);
printf("\n\nDo you wish to continue? \n");
printf("\nType '1' for Yes or '2' for No!\n\n");
scanf("%d", &guessGame);
}
}
else {
printf("\nYou did not enter a digit\n");
printf("\n\nPlease enter a number between 1 and 10:\n\n");
scanf("%d", &iResponse);
}
}
else {
printf("\nThe window will now close. Try again later!\n");
exit(0);
}
}while(guessGame != NO);
}
The code goes into infinite loop as scanf() is unable to read an integer. The character you entered remains in the keyboard buffer.No more reading of integers is possible as long as the character is present in the buffer. scanf() simply returns the number of items read as 0 each time. Hence,the program does not wait for the user to enter data and infinite loop results.
scanf() returns number of items successfully read. So,you can simply check for the return value of scanf(), if its 1 then scanf() has correctly read an integer.
check = scanf("%d", &iResponse);
if(check == 1){
printf("\nThank you\n");
printf("\nYou entered %d\n", iResponse);
and flush the buffer if wrong input is entered
else {
while (getchar() != '\n'); //flush the buffer
printf("\nYou did not enter a digit\n");
printf("\n\nPlease enter a number between 1 and 10:\n\n");
//scanf("%d", &iResponse);
}
no need to ask for input here, while loop will continue and prompt for input in the beginning
Trying taking the input in the form of string .. also u will have to compare the input in the form 'number' :)
This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 4 years ago.
I want to know the reason why this code not run properly
#include<stdio.h>
main()
{
char a;
int n;
do
{
printf("enter the number");
scanf("%d",&n);
printf("the squre is %d",n*n);
printf("want any more so Y for yes N for no");
scanf("%c%[^\n]",&a);
}while(a=='Y');
}
Reasons are
1. scanf("%c%[^\n]",&a); needs two parameters. Remove %[^\n].
2. \n character left behind by the previous scanf on pressing Enter key. Next scanf will read this \n character in the buffer. You need to consume this \n. Use a space before %c specifier to eat up this \n.
Try this:
scanf(" %c",&a);
↑ A space before %c specifier
A space before %c specifier is able to eat ant number of newline characters.
Your code after modification:
#include<stdio.h>
int main(void)
{
char a;
int n;
do
{
printf("enter the number\n");
scanf("%d",&n);
printf("the squre is %d\n",n*n);
printf("want any more so Y for yes N for no\n");
scanf(" %c",&a);
}while(a=='Y');
return 0;
}
Here is a solution to your problem.
#include<stdio.h>
main()
{
char a;
int n;
do
{
printf("enter the number");
scanf("%d",&n);
a = getchar(); // <-- Here is a change.
printf("the squre is %d",n*n);
printf("want any more so Y for yes N for no");
while(a == '\n') a = getchar();
}while(a=='Y');
}
What actually is making you problem is this line.
scanf("%d",&n);
Suppose, you entered 10 then pressed 'Enter', now scanf() takes 10 and leaves a newline behind in the buffer. It is making problem. By getchar() you are eating up that new line each time after taking a input with scanf. Yes there are other solutions too with scanf() tricks but it seems simpler to me. So I shared it.
just use scanf(" %c",&a); and could be done.
Wrong code: scanf("%c%[^\n]",&a);
Right code: scanf(" %c%*[^\n]",&a);
This question already has answers here:
Scanf skips every other while loop in C
(10 answers)
Closed 8 years ago.
#include "stdio.h"
int main(void)
{
int order, nextp, N=3;
char cont;
nextp = 0;
printf("\nShould we continue (y or n): ");
scanf("%c", &cont);
if (cont != 'y') return;
for(; nextp < N; nextp++)
{
printf("Enter order number: ");
scanf("%d", &order);
printf("you have entered %d\n", order);
printf("okay now continue with cont\n");
printf("enter cont y or n: ");
scanf("%c", &cont);
if (cont != 'y')
{
printf("\nnot equal to y\n");
break;
}
printf("after intepreting t[0]");
}
return 0;
}
The output looks like this
Should we continue (y or n): y
Enter order number: 45
you have entered 45
okay now continue with cont
enter cont y or n:
not equal to y
The second input was skipped. Why?
because of newline character already in stdin , this is happening.
use
scanf(" %c", &cont);
instead of
scanf("%c", &cont);
note one space before %c.
After scanf("%d", &order); consumes the number (45 in this case), there is still a newline left after that. You can use scanf("%d\n", &order) to make it consume the return.
Another answer to this can be found here:
scanf() leaves the new line char in buffer?
This is why scanf is not typically preferred for character input. There's a left over carriage return after the previous input.
For example, if you were to add a getchar() after the order input, your problem would be solved, but that's not clean code. You can also see this explicitly by subsituting cont != 'y' to cont != '\n'.
Instead, use getchar() for all your input and check for \n
For most conversions scanf will skip whitespace, but for char format ("%c") you must skip white space by using an explicit space in the format (" %c") as explained here:
C - trying to read a single char
This is also explained in the scanf documentation, but it's confusing and may be better to use something else as others have mentioned.
You can use fflush()
printf("enter cont y or n: ");
fflush(stdin);
scanf("%c", &cont);