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;
}
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:
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'.
I would like to know about the getchar() logic in the following codes...
printf("Type up to 25 characters and then press Enter. . . \n") ;
for (i = 0; i < 25; i++)
{
msg[ i] = getchar() ;
if (msg[ i] == ' \n' )
{
i--;
break;
}
}
putchar(' \n' ) ;
for (; i >= 0; i--)
{
putchar(msg[ i] ) ;
}
In the above code if i input a name,say "STACKEXCHANGE" and then hit enter it will display the word properly..but the below code works differently..
printf("What are your two initials?\n") ;
firstInit = getchar() ;
lastInit = getchar() ;
In this example, if i type "ST" and then hit enter, 'S' will be stored in firstinit, while "\n" will be stored in lastInit instead of 'T'.
How does this happen? Isn't 'T' the second character input into the buffer. Infact \n is the third character in the buffer. so why does \n get stored. correct me if iam wrong, but the buffer is released when \n is pressed or entered, then why is it again being stored in the next getchar() function.
Why is the first code executed differently then? I mean if i input "stackexchange" and hit enter "t" is stored as the second character as is wanted, but it in the second example if the same "st" is typed and "enter' is input, the "t" is not stored as the second input, but instead "enter' is taken as the second input.
I am sorry if my typing is confusing... basically i want to know the logical flow in both codes, how it happens behind the scene..
the only reason for storing \n is when you are entering S the pressing enter and not flushing out the carriage return so it will store \n in your second string.
firstInit = getchar() ;
will read and store S
lastInit = getchar() ;
will read and store carriage return
getchar() is a standard library function which will read a character from the console.
Check the below code which takes your input ST and stores it in 2 char's a and b.
int main(void){
char a;
char b;
a = getchar();
b= getchar();
printf("a = %c b = %c\n",a,b);
return 0;
}
Input
ST<enter>
Output
a = S b = T
If you are seeing a newline char being saved into b here then the input is like S<enter> not ST<enter>