为什么字符串比较不能按预期工作

Why does string comparison not work as expected

我是(求三角形或正方形或圆形的面积,值基于用户输入)我做的。没有任何错误,但我认为函数的位置不正确。每当我键入要查找的 SHAPE 时,它都会立即转到 ELSE 语句(“OTHER SHAPE NOT AVAILABLE”)。你们能帮我看看哪里出了问题吗?

#define pi 3.14

int areaTriangle (int valueBase, int valueHeight);
int areaSquare (int valueSide);
int areaCircle (int valueRadius);

int main() {
 
    // program
    while (1) {

        char shape[20];

        printf("what geometry shape do you want to find? (TRIANGLE/SQUARE/CIRCLE) =");
        fgets(shape, 20, stdin);

        if ( strcmp(shape, "TRIANGLE") == 0) {
            int height;
            int base;

            printf("height = ");
            scanf("%d", &height);
            printf("base = ");
            scanf("%d", &base);

            // INPUT TRIANGLE AREA FUNCTION
            areaTriangle (height, base);
        }

        else if ( strcmp(shape, "SQUARE") == 0) {
            int side;

            printf("side = ");
            scanf("%d", &side);
        
            // INPUT SQUARE AREA FUNCTION
            areaSquare (side);
        }

        else if ( strcmp(shape, "CIRCLE") == 0) {
            int radius;

            printf("radius = ");
            scanf("%d", &radius);
        
            // INPUT CIRCLE AREA FUNCTION
            areaCircle (radius);
        }

        else
            printf("OTHER SHAPE NOT AVAILABLE\n");

    }
    return 0;
}

int areaTriangle (int valueBase, int valueHeight) {
    int area = (valueBase*valueHeight) / 2;

    return printf("The area of this triangle is = %d", area);
}

int areaSquare (int valueSide) {
    int area = valueSide * valueSide;

    return printf("The area of this square is = %d", area);
}

int areaCircle (int valueRadius){
    int area = pi * valueRadius * valueRadius;

    return printf("The area of this circle is = %d", area);
}
```

因为the fgets function可以在它写入的缓冲区中保留换行符。

要么您需要更新您的比较以包括换行符:

strcmp(shape, "TRIANGLE\n")

或者在使用字符串之前删除换行符:

while (fgets(shape, 20, stdin) != NULL)
{
    // Replace the newline with the string terminator
    shape[strcspn(shape, "\n")] = '[=11=]';

    if (strcmp(shape, "TRIANGLE") == 0) { ... }
    ...
}