Home > Mobile >  how to use if else c
how to use if else c

Time:11-18

How do you provide a condition in the if statement, if the variable is an integer data type then it will be displayed, and if the variable is any other data type then something else will be displayed?

#include <iostream>
#include <stdlib.h>
#include <windows.h>
#include <conio.h>
using namespace std;

int main() {
    char pilih,pilih2;
    int p, l, a, t, r,ulang = 4;
    float luas1, luas2, luas3, keliling1, keliling2, keliling3, phi = 3.14;
    
    while (ulang > 0) {
        pilihUlang:
        cout << "Pilih jenis bangun datar berikut :\n 1. Persegi panjang\n 2. Segitiga sama sisi\n 3. Lingkaran" << endl;
        cout << "Masukan pilihan anda [1/2/3] : ";
        cin >> pilih;
        system("cls");
        switch (pilih) {
        case '1':
            system("color 07");
            cout << "Luas Dan Keliling Persegi Panjang" << endl;
            cout << "Masukan Panjang = ";
            cin >> p;
            if (?) { // <-- here
                cout << "Masukan Lebar = ";
                cin >> l;
                system("cls");
                cout << "Luas dan keliling Persegi Panjang dengan panjang " << p << " dan lebar " << l << ", yaitu :" << endl;
                luas1 = p * l;
                keliling1 = 2 * (p   l);
                cout << "Luas = " << luas1 << endl;
                cout << "Keliling = " << keliling1 << endl;
                cout << "Sisa bisa memilih ulang " << ulang - 1 << " kali." << endl;
                break;
            }
            else {
                //...
            }

CodePudding user response:

From the istream::operator>> man page:

If extraction fails (e.g. if a letter was entered where a digit is expected), zero is written to value and failbit is set.

So, your function could test the cin.good() method to see if the >> operation was successful, like this:

cin >> p;
if (cin.good()) {
   cout << "The integer you typed was " << p << endl;
} else {
   cout << "Hey, that wasn't an integer!" << endl;
}
  • Related