Typing e (to double) breaks up program!

In a exercise from a book, it asked me to take in a double and a unit, convert everything to meter, and as I enter values, print "smallest so far" or "largest so far".
The code works, and even takes care of wrong input such as 3fg.
The problem is if I type 3e, the program breaks.
Output :
Enter your number and unit: 5m
Enter your number and unit: 2cm
Smallest so far!
Enter your number and unit: 3ym
Wrong unit!
Enter your number and unit: 700in
Largest so far!
Enter your number and unit: 3e

//program breaks, ie I get ephraim@universal:~/Desktop/cpp_playground$, the terminal's prompt
Also, is there a way to prevent this overusing of bool?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
  
#include "std_lib_facilities.h"

 
    constexpr double cm_to_meter = 0.01; // 5 cm = 5 * 0.01 = 0.05m
	constexpr double inch_to_meter = 0.0254; 
	constexpr double ft_to_meter = 0.3048; //1 ft = 30.48 cm
	bool wrong_unit = false;


double unit_convert(double a, string unit){
	if(unit == "cm"){
		wrong_unit = false;
		return a * cm_to_meter;}

	else if(unit == "m"){ // in ft
		wrong_unit = false;
		return a;}

	else if(unit == "in"){
		return a * inch_to_meter;
		wrong_unit = false;}

	else if(unit == "ft"){
		return a * ft_to_meter;
		wrong_unit = false;}

	else {
		cout << "Wrong unit!\n";
		wrong_unit = true;}
}

int main(){

	


	double a;
	string unit;
	
	wrong_unit = true;
	while(wrong_unit){ // Just to repeat this loop as long as the unit is wrong
		cout << "Enter your number and unit: ";
	cin >> a >> unit;
	a = unit_convert(a,unit);
}




	double small = a;
	double large = a;

	cout << "Enter your number and unit: ";
	while(cin >> a >> unit){
		a = unit_convert(a,unit);
		if(wrong_unit) {
			cout << "Enter your number and unit: ";
			continue;
		}
		if(a < small){
			cout << "Smallest so far!\n";
			small = a;}
		else if(a > large){
			cout << "Largest so far!\n";
		    large = a;}
		else
			cout << a << unit << " did not break any records.\n";
		cout << "Enter your number and unit: ";
	}



cout << "\n";
}

Last edited on
That's probably because 'e' is still part of your double. These are all valid double values:
1
2
3
4
double x = 0.05;
double y = 500.0;
double z = 5e2; // 500
double w = 5e-2; // 0.05 

'e' means 'exponent', and a double of XeY means X*10Y

The simplest solution is to simply request a space between your number and your unit.
Last edited on
The simplest solution is to simply request a space between your number and your unit.

But the question asks me to make it work both ways - with a space and without one.
Topic archived. No new replies allowed.