0

After compiling a console application and entering wrong data it gives strange output value, like 2.0434e-006, while it was requesting numerals. Here is the code:

#include <iostream>
#include <conio.h>

int main() {
    using namespace std;
    float l,w,h;
    float s;
    cout << "\nCalculating surface area of the parallelepiped\n";
    cout << "Enter the raw data:\n";
    cout << "Length (cm)  -> ";
    cin >> l;
    cout << "Width (cm) -> ";
    cin >> w;
    cout << "Height (cm) -> ";
    cin >> h;
    s = (l*w + l*h + w*h)*2;
    cout << "Surface area: " << s << " sq. cm\n";
    cout << "\n\nPress any key...";
    getch();
    }

I heared something about IEEE 754 floating-point faults, but even this information doesn't make me sure in my knowledge.

Cœur
  • 37,241
  • 25
  • 195
  • 267

1 Answers1

3

Values of uninitialized non-static local variables are indeterminate.

Check if the input succeeded and handle errors.

#include <iostream>

int main() {
    using namespace std;
    float l,w,h;
    float s;
    cout << "\nCalculating surface area of the parallelepiped\n";
    cout << "Enter the raw data:\n";
    cout << "Length (cm)  -> ";
    if (!(cin >> l)) {
        cout << "input error\n";
        return 1;
    }
    cout << "Width (cm) -> ";
    if (!(cin >> w)) {
        cout << "input error\n";
        return 1;
    }
    cout << "Height (cm) -> ";
    if (!(cin >> h)) {
        cout << "input error\n";
        return 1;
    }
    s = (l*w + l*h + w*h)*2;
    cout << "Surface area: " << s << " sq. cm\n";
    cout << "\n\nPress any key...";
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • After error handling it closes application. How can I prevent it? –  Mar 13 '16 at 02:57
  • Sorry, but how? When I enter a letter to variable, it closes an application after cout'ing the error message. I need it to return back to cin. –  Mar 13 '16 at 03:02
  • @Frodgy in that case you need to flush input, clear cin error flags, and use a control structure so that execution returns to input again – M.M Mar 13 '16 at 04:25
  • Thanks for the answer, but I questioned, why it gives a random number after cin when we give any other value, but not the int's one. After making the while-construction, it obviously works (http://stackoverflow.com/questions/18567483/c-checking-for-an-integer). –  Mar 14 '16 at 20:09