C语言:Turbo C,DOS,输入=4。输出=$ $$ $$$ $$$$。对字符输入进行无限循环。小号

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

用户提供输入,因此必须打印图案。它应该遇到负数和字符作为输入。我遇到了负值作为输入,但当我尝试提供 char 输入时,它进入了无限循环。那么我怎么会遇到 int 数据类型的 char 值作为输入。

#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
    }
}```

当您执行 scanf("%d",&numberOfLines); 时,您想要读取一个整数。如果您随后输入一个字母,例如 a,则不会从输入流中读取任何内容。换句话说,您将进入一个无限循环,您一直在尝试读取一个整数,但流中包含一个字母。

您需要从流中删除该字母。

你可以试试:

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

但是,如果输入流失败,这将导致问题。

更好的解决方案是使用fgetssscanf

这是 printPattern

的更短、更简单的版本
void printPattern(int n)
{
    char dollar[n];
    memset(dollar, '$', n);

    for(int i = 1; i <= n; ++i)
        printf("%.*s\n", i, dollar);
}