Your problem is that the %c
conversion specifier doesn't cause scanf()
to skip leading whitespace. You need to handle the newline character that's still in the stream after reading your input.
The input stream is empty when scanf()
is called the first time through the loop, so it waits for you to type something. You type s
and hit the Enter key, so the input stream contains the characters s
and \n
(newline). scanf()
removes the s
from the input stream and assigns it to op
. When scanf()
is called the second time, the input stream is not empty; it still has the \n
character in it, so scanf()
reads it and assigns it to op
, which causes the loop condition to fail, so your loop exits.
There are several ways to get around this problem. I'm going to recommend reading strings as opposed to individual characters using fgets()
, as follows:
char op[3] = {0}; // input character + newline character + 0 terminator
do
{
printf("¿Sigues?");
if (fgets(op, sizeof op, stdin))
{
/**
* Check for a newline character in the input. If it's not there
* then the user typed in too many characters. In order to keep
* the input stream from getting clogged up with bad input, read
* until we find a newline character.
*/
char tmp[3];
char *newline = strchr(op, '\n');
while (!newline && fgets(tmp, sizeof tmp, stdin))
{
newline = strchr(tmp, '\n');
}
}
else
{
printf("Error while reading input\n");
op[0] = 0;
}
} while (tolower(op[0]) == 's');