Question

I am trying to make the program print out "OK" for as long as i enter 'y' as a choice at the end, but it is not looping, it just prints out "OK" and ends the program even if i enter a 'y' at the end. Please help.

#include <stdio.h>
int main()
{
    char c = 'y';
    while (c == 'y')
    {
        printf_s("OK\n");
        scanf_s("%c", &c);
        if (c != 'y')
        {
            break;
        }
    }
    return 0;
}
Was it helpful?

Solution

On first iteration when you press Enter key then a newline character \n is passed to the input along with y. On second iteration scanf_s reads \n. Change

scanf_s("%c", &c);  

to

scanf_s(" %c", &c);  
         ^Notice the space before %c  

A space before %c specifier can consume any number of white-space characters.

OTHER TIPS

Change the scanf_s line as follows

scanf_s("%c", &c, 1);

This extra parameter is specifying the size of the c argument. Plain old scanf doesn't require this argument but the versions ending with _s do

Also the if block with the break statement is unnecessary because the conditional on the while loop effectively does the same thing. It could be written as follows

while (c == 'y')
{
    printf_s("OK\n");
    scanf_s("%c", &c, 1);
}

You are wrong with scanf

if you use like this u will see it is working ..

       #include <stdio.h>

int main()
{
    int c = 1;
    while (c == 1)
    {
        printf_s("OK\n");
        scanf_s("%d", &c);
        if (c != 1)
        {
            printf_s("hello\n");
                continue;
        }

    }
    return 0;
}

OK I used scanf instead of scanf_s, that solved the problem, thanks everyone.

Put a space before %c to skip whitespace.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top