使用scanf(“%c”)时,我的代码不起作用

时间:2016-10-24 21:39:06

标签: c

所以我有这个代码,意味着需要两个用户输入“int height”和“char symbol”。然后代码将调用一个函数,该函数将创建一个ascii的三角形,它是“高”线高,并用ascii“符号”填充。

然而。当我尝试获取符号的用户输入时。该程序跳过它并崩溃。我注意到,只有当我在它之前调用高度时才会发生这种情况。我不知道为什么。任何帮助将不胜感激!

void print_triangle(int height, char symbol)
{

    for (int i = 0; i < height; i++)
    {
        printf("\n");

        for (int j = 1; j < (height - i); j++) //this will print the correct amount of spaces per line to shape the triangle
        {
            printf(" ");
        }

        printf("/"); // printf one side of triangle 

        for (int k = 0; k < (i * 2); k++)  // print the correct number of symbols per line to fill the triangle
        {
            printf("%c", symbol);
        }

        printf("\\");  // print the other side of the triangle

    }

    printf("\n");  // next line
}


int main()
{
    int height;
    char symbol;

    printf("Height? ");
    scanf("%d", &height);   // read triangle height

    printf("Symbol? ");
    scanf("%c", &symbol);  // THIS IS WHERE THE PROBLEM OCCURS. I CANT READ THE SYMBOL.

    print_triangle(height, symbol);   //call function

    return 0;
}

0 个答案:

没有答案