This question already has answers here:
Scanf skips every other while loop in C
(10 answers)
Closed 6 years ago.
My problem is that the scanf for the character is skipped and it doesn't check scan the char to see if I want to repeat the program again or not so why this is happening?
#include <stdio.h>
#include <stdlib.h>
int main()
{
int number,check;
char rep;
printf("Program to check if number is even or odd");
while( (rep!='N') || (rep!='n') )
{
printf("\n\nPlease enter the number: ");
scanf("%d",&number);
check = number%2;
if(check != 0)
printf("\nNumber is odd.");
else
printf("\nNumber is even.");
printf("\n");
printf("Do you want to enter number again?\nY=yes\tN=no\n");
scanf("%c", &rep);
}
return 0;
}
Change scanf("%c", &rep); to scanf(" %c", &rep);.
This is because a '\n' is left in stdin the first time you input a number. When executing scanf("%c", &rep);, that '\n' is immediately consumed by scanf() and assigned to rep. Since '\n' is equal to neither 'N' nor 'n', that loop continues.
With the leading space in the format string, all whitespace characters are discarded before reading starts. In your case, the invisible '\n' will be ignored, so that you can input a character.
Also, you should write char rep = 0; instead, in case the original value of rep happens to be 'n' or 'N'.
Related
This code is supposed to -
Count the number of characters from input sequence.
Repeat the action until user exits the program.
Use nested do-while loop to achieve this purpose.
But the inner loop is executed only once.
Why?
#include <stdio.h>
int main ()
{
int x;
char i, ans;
i = '\0';
do
{
i = '\0';
x=0;
printf("\nEnter sequence of character:");
do
{
i = getchar();
x++;
}
while(i!='\n');
printf("\nNumber of characters entered is: %d", --x);
printf("\nMore sequences (Y/N) ?");
ans = getchar();
}
while(ans =='Y' || ans == 'y');
After you read the answer yes/no (the line with ans = getchar();), you'll read an "y" and a "\n". You'll consume the "y" and process it, but the next iteration when you read i = getchar();, i will consume the remaining "\n", so will break that do-while loop.
Although it's not my favourite solution, a simple workaround is this:
#include <stdio.h>
int main ()
{
int x;
char i, ans;
i = '\0';
do
{
i = '\0';
x=0;
printf("\nEnter sequence of character:");
do
{
i = getchar();
x++;
}
while(i!='\n');
printf("\nNumber of characters entered is: %d", --x);
printf("\nMore sequences (Y/N) ?");
ans = getchar();
getchar();
}
while(ans =='Y' || ans == 'y');
}
So just consume that extra "\n". This will work only if you type "y" followed by "\n" in terminal. If you type any extra characters, you'll have undefined behaviour.
Note: In your version, try to type: "y1234" then enter when prompted if you want to input again. You'll see that in fact the nested do-while loop works and will count the 4 characters after "y".
What happened:
getchar is a macro that gets a character from stdin.
The delimiter ('\n' in this case) is counted as a separate
character that remains in the buffer and is retrieved the next time
getchar() is called.
This causes inner loop to exit.
What could be done:
Insert the following after ans = getchar();
i = getchar();
if(i != '\n')
ungetc(i,stdin);
New code explained:
ungetc(int x,FILE *stream) pushes a character back into input stream.
stdin is the standard input stream defined in <stdio.h>.
We are reading a character and putting it back if it is not '\n'.
Not exactly sure, but I think that when the user presses enter to finish the 1st input character the input buffer keeps then enter button as the \n character. Try adding if(i == '\n') getChar(); after the x++;.
This question already has answers here:
Clarification needed regarding getchar() and newline
(4 answers)
Closed 4 years ago.
I have this following code.
#include <stdio.h>
int main () {
char letter1;
char letter2;
printf("Enter Letter 1: ");
letter1 = getchar();
printf("\n");
printf("Enter Letter 2: ");
letter2 = getchar();
printf("\n");
printf("%c - %c\n", letter1, letter2);
return(0);
}
I am trying to use getchar() to define letter1 and letter2, however it will only work for letter1, then set the value of letter2 to '\n'. Does anyone know a work around for this, so I can type values for both variables?
This is because when you press the first letter and type the Enter key, you send the codes for the letter and the '\n' one after the other to the input buffer from where it will be consumed.
So the first getchar() get the code for the letter you typed and thus the letter is removed from the input buffer but that of \n remains which is consumed by the next getchar().
Inorder to avoid this, you need to keep consuming from the input buffer till the '\n' is consumed.
One way of doing this is
int c;
while( (c=getchar())=='\n' && c!=EOF);
This will keep on consuming from the input buffer as long as the read character is a \n and EOF is not reached. getchar() would return EOF on error.
int letter1, letter2;
int c;
printf("Enter Letter 1: ");
letter1 = getchar();
printf("\n");
printf("Enter Letter 2: ");
while( (c=getchar())=='\n' && c!=EOF);
letter2=c;
printf("\n");
printf("%c - %c\n", letter1, letter2);
Edit: As pointed out in the comments, note that getchar() returns an int and not a char. See this post.
This question already has answers here:
Scanf skips every other while loop in C
(10 answers)
Closed 6 years ago.
My problem is that the scanf for the character is skipped and it doesn't check scan the char to see if I want to repeat the program again or not so why this is happening?
#include <stdio.h>
#include <stdlib.h>
int main()
{
int number,check;
char rep;
printf("Program to check if number is even or odd");
while( (rep!='N') || (rep!='n') )
{
printf("\n\nPlease enter the number: ");
scanf("%d",&number);
check = number%2;
if(check != 0)
printf("\nNumber is odd.");
else
printf("\nNumber is even.");
printf("\n");
printf("Do you want to enter number again?\nY=yes\tN=no\n");
scanf("%c", &rep);
}
return 0;
}
Change scanf("%c", &rep); to scanf(" %c", &rep);.
This is because a '\n' is left in stdin the first time you input a number. When executing scanf("%c", &rep);, that '\n' is immediately consumed by scanf() and assigned to rep. Since '\n' is equal to neither 'N' nor 'n', that loop continues.
With the leading space in the format string, all whitespace characters are discarded before reading starts. In your case, the invisible '\n' will be ignored, so that you can input a character.
Also, you should write char rep = 0; instead, in case the original value of rep happens to be 'n' or 'N'.
This question already has answers here:
getchar() skips every other char in C
(2 answers)
Closed 7 years ago.
Can anybody tell me why the line o = getchar(); works properly only the first time and then once works, once it's not?
#include <stdio.h>
int main(void)
{
char o;
for (int i = 1; i > 0; i++)
{
printf("%d\n", i);
if (i % 10 == 0)
{
printf("Do you want to continue? (y/n): ");
o = getchar();
if (o == 'n')
break;
}
}
return 0;
}
First of all, getchar() returns an int, which may not fit into a char. Change
char o;
to
int o = 0;
Then, to come to the point of the skipping, well, it actually do not skip. When you press any key and press ENTER, the newline from the press of the ENTER key serves as the feed to the getchar() in every second iteration of the loop.
As Sourav Ghosh stated, the problem is the newline character. Once you type something in the console and press "Enter" afterwards, the text is in the input buffer. This buffer is then read by getchar. However, getchar only reads one character with each call. The problem is, that "Enter" is interpreted as a character ('\n') and is hold in the buffer, getchar is going to read it as an individual character. The next call of getchar will read the newline character, rather than the wanted character.
Solution: You could call getchar (after your actual call) until the newline is reached, thus clearing the read line inside the buffer.
while (getchar() != '\n')
;
Or just build a little function
int nextch() {
int ch = getchar();
while (getchar() != '\n')
;
return ch;
}
In my code given below if I press 'y' for once it will reapeat, but then it is not asking for next tome to repeat (or press 'y').Can someone help why this code is terminated after one loop?
main()
{
char choice;
do
{
printf("Press y to continue the loop : ");
scanf("%c",&choice);
}while(choice=='y');
}
That will be because stdin is buffered. So you are probably entering the string of a y followed by a \n (newline character).
So the first iteration takes the y, but the next iteration doesn't need any input from you because the \n is next in the stdin buffer. But you can easily get around this by getting scanf to consume the trailing whitespace.
scanf("%c ",&choice);
NOTE: the space after the c in "%c "
But, your program can get stuck in an infinite loop if the input ends with a y. So you should also check the result of the scanf. e.g.
if( scanf("%c ",&choice) <= 0 )
choice = 'n';
You should read out the newline character after that scanf() call. Otherwise, that gets into choice the next time around and so the while loop comes out.
#include<stdio.h>
int main()
{
char choice;
do
{
printf("Press y to continue the loop : ");
choice = getchar();
getchar();
}
while(choice=='y');
return 0;
}
At the first character of the scanf format string, insert a space. This will clear out all white space characters from stdin before reading data.
#include <stdio.h>
int main (void)
{
char choice;
do
{
printf("Press y to continue the loop : ");
scanf(" %c",&choice); // note the space
}while(choice=='y');
return 0;
}