cturbo-c

C lang: Turbo C, DOS, Input = 4. Output =$ $$ $$$ $$$$. Going infinite loop for char input. S


User gives input and accordingly the pattern must be printed. It should encounter negative numbers and char as input. I encounterd the negative value as input but as I try to give char input it goes on ifinite loop. So how can I encounter char value for int data type as an input.

#include<stdio.h>
#include<conio.h>
/*
C program to print the pattern allowing user
to input the no. of lines.
*/

//Declaring method for printing pattern
void printPattern(int numberOfLines);

void main()
{
    char userChoice;//User's choice to continue or exit
    int numberOfLines;//User's input for number line to be printed

    clrscr();

    //Logic for printing the pattern
    do
    {
        printf("Enter the number of lines you want to print \n");
        scanf("%d",&numberOfLines);

        //Countering issue if user enters a char insted of number
        /*while()
        {
            printf("Enter number only \n");
            scanf(" %c",&numberOfLines);
        }*/

        //Countering issue if user enters negative number
        while(numberOfLines<=0)
        {
            printf("Enter positive number \n");
            scanf("%d",&numberOfLines);
        }

        //Calling method to the start printing of method
        printPattern(numberOfLines);

        //Taking user's choice to continue or not
        printf("Press Y to continue else any other key to exit \n");
        scanf(" %c",&userChoice);
    }
    while(userChoice == 'y' || userChoice == 'Y');
}

/*
Method  definition for printing the pattern
Argument numberOfLines: User's input for number of lines
*/
void printPattern(int numberOfLines)
{
    int i,j;
    for(i=0 ; i<numberOfLines ; i++) //for rows
    {
        for(j=0 ; j<=i  ; j++) //for columns
        {
            printf("$");
        }
        printf("\n"); //for going to next row after printing one
    }
}```

Solution

  • When you do scanf("%d",&numberOfLines); you want to read an integer. If you then enter a letter, like an a, nothing will be read from the input stream. In other words, you'll go into an endless loop where you keep trying to read an integer but the stream contains a letter.

    You need to remove that letter from the stream.

    You could try:

    while(scanf("%d",&numberOfLines) != 1)
    {
        // Didn't get an integer so remove a char
        getchar();
    }
    

    However, that will lead to problems if the input stream fails.

    The better solution is to use fgets and sscanf