Reputation: 35
This code is supposed to -
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');
Upvotes: 1
Views: 298
Reputation: 11
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++;
.
Upvotes: 1
Reputation: 1197
What happened:
getchar
is a macro that gets a character from stdin
.'\n'
in this case) is counted as a separate
character that remains in the buffer and is retrieved the next time
getchar()
is called.What could be done:
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>
.'\n'
.Upvotes: 1
Reputation: 1479
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"
.
Upvotes: 2