Search code examples
cwhile-loopgetchar

My code dont see a whille loop in C (with a getchar function)


My program doesnt see the while loop and i cant enter my stiring to c variable

i want to enter a string. if a char in this string will be a number he will stay as a number if he doesnt be a number he will change to char 'num' place farther in ascii code.

#include <stdio.h>
#include <ctype.h>

int main()
{

    int num;
    char c;

    printf("Enter number: \n");
    scanf("%d", &num);

    printf("Enter a string : \n");
    while ((c = getchar()) != '\n')
    {
        if (isdigit(c))
        {
            putchar(c);
        }
        else
        {
            putchar(c + num);
        }
    }

    return 0;
}

Solution

  • With both scanf() and getchar(), you generally have to press the [return] key after the desired key. Both the desired key, and the return key, are (usually) placed in the stdin stream. The question code neglected to take this in consideration. Hence, the first desired key was read by scanf() and stored in num, but left the return key '\n' in the buffer; which was then later read by the getchar() and stored in c. Hence the loop exit criteria was satisfied, and the program terminated.

    Somehow, the code, to be functional, must read the unwanted return key '\n' left behind by the call to scanf(); and perhaps also for the getchar().

    Perhaps something like:

    #include <stdio.h>
    #include <ctype.h>
    
    int main()
    {
        int num;
        int c;
        char cr[2];
        printf("Enter number: \n");
        scanf("%d%1[\n]", &num, cr);  // Reads %d into num, and garbage '\n' into cr.
        printf("Enter a string : \n");
        while((c = getchar()) != '\n')
        {
            if(isdigit(c))
                putchar(c);
            else
                putchar(c + num);
            getchar(); // Reads garbage '\n' from previous getchar()
        }
        printf("\n");
        return 0;
    }