1

I am writing a simple program in C but I have a problem. As you see from the code below, I have only one while loop but the program execute after certain choices without we select.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <windows.h>


double area_of_triangle(double, double, double);

int main(){
    SetConsoleTitle("Calculate Triangle Area");

    char pilihan;
    double a, b, c, area2;

    while(1)
    {
        printf("\n\n\t1. Triangle Area\n");
        printf("\t2. Out");

        printf("\n\nSelect your choice:");
        scanf("%c", &pilihan);

        switch(pilihan){
        case '1':
            printf("\t\t\tFind The Area Of A Triangle\n");
            printf("\tArea Of A Triangle:\n\n");
            printf("\tFirst:");
            scanf("%lf", &a);
            printf("\tSecond:");
            scanf("%lf", &b);
            printf("\tThird:");
            scanf("%lf", &c);

            area2 = area_of_triangle(a, b, c);
            printf("\n\n\tTriangle Area = %.2lf\n\n", area2);
            break;
        case '2':
            exit(0);
            break;
        default:
            printf("\n\n\t\t\tINVALID!!! 1 OR 2 ONLY\n");
            break;
        }
    }

    return 0;
}

double area_of_triangle(double a, double b, double c){

  double s, area2;

  s = (a+b+c)/2;

  area2 = sqrt(s*(s-a)*(s-b)*(s-c));

  return area2;
}

This is the output:

        1. Triangle Area
        2. Out

Select your choice:1
                        Find The Area Of A Triangle
        Area Of A Triangle:

        First:423
        Second:423
        Third:423


        Triangle Area = 77478.53



        1. Triangle Area
        2. Out

Select your choice:

                        INVALID!!! 1 OR 2 ONLY


        1. Triangle Area
        2. Out

Select your choice:

As you saw, the program executed and choose default value itself which is INVALID!!! 1 OR 2 ONLY without any input and press enter. I would be very grateful if you could help me solve this problem. Thank you...

Ridz
  • 19
  • 2

1 Answers1

0

When you use scanf() to read characters, it leaves the newline character in the buffer, so the next time scanf() is encountered, it consumes the newline character and leaves you with the invalid results you're getting.

To avoid this problem, you can format scanf() to consume the newline, like this:

        printf("\n\nSelect your choice:");
        scanf("%c\n", &pilihan);
Jonathon Anderson
  • 1,162
  • 1
  • 8
  • 24