Reputation: 13
I've tried to use character data type to compare in variable reply
if equal to y
it will continue calling the function recursion()
, however, it did only 1 recursion()
call and the program terminated. This only work if I use the int data type, as the variable to compare. Please anyone can let me know why this happen?
#include <stdio.h>
void recursion()
{
char reply;
printf("Continue?:");
reply=getchar();
if(reply=='y')
{
printf("Continued\n");
recursion();
}
}
int main()
{
recursion();
return(0);
}
output:
Laptop1:User1$ ./recur
Continue?:y
Continued
Continue?:Laptop1:User1$
Upvotes: 1
Views: 161
Reputation: 727137
The problem is that when end-users enter 'y'
in the terminal, they press Enter. This inserts another character into the stream - '\n'
. That is the character that the next call to getchar()
would return, ending the chain of calls due to
if(reply=='y')
condition evaluating to "false".
You can fix the problem in several ways - for example, by using scanf
:
if (scanf(" %c", &reply) == 1 && reply == 'y')
// ^
// Note the space above
Adding a space character in front of %c
ensures that scanf
skips whitespace characters before reading the character into reply
variable.
Upvotes: 0
Reputation: 75062
getchar()
will read newline character if it is, and it will prevent it from continueing.
Try this:
#include <stdio.h>
int getchar2()
{
int c;
do
{
c = getchar();
} while (c == '\n'); /* ignore newline characters */
return c;
}
void recursion()
{
int reply;
printf("Continue?:");
reply=getchar2();
if(reply=='y')
{
printf("Continued\n");
recursion();
}
}
int main()
{
recursion();
return(0);
}
Upvotes: 3