Stroustrup book problem with code example

Hi folks? I need an advise.
I have problem with code
I don't understand the matter of it doesn't work:
the problem is every time i see the finale line:
"I don't understand."
thank you so much
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
 #include "pch.h"
#include <iostream>
#include "std_lib_facilities.h"

int main()
{
	constexpr double cm_per_inch = 2.54;
	double length = 1;
	char a = ' ';
	cout << "pleas enter length" <<" "<< "and the unit of measure (c or i): \n";
	cin >> length >> a;
	switch (a)
	{
	case 'i':

		cout << length << "inch== " << cm_per_inch * length << "cm \n";

		break;

	case 'c':
			cout << length << "cm== " << length / cm_per_inch << "inch\n";
			break;
	default:
			cout << "I don't understand.";
			break;
	}
Last edited on
What are you entering as the input?
This what what I'm getting when I compile and run your program:


pleas enter length and the unit of measure (c or i): 
1i
1inch== 2.54cm

pleas enter length and the unit of measure (c or i): 
1i
1inch== 2.54cm


also for other inputs:

pleas enter length and the unit of measure (c or i): 
3213o
I don't understand
Last edited on
Stroustrup book problem with code example

Which chapter of which book of his?
fiji885 (234) thanks fore help!
every time when i entered (c or i) or any other literal in "char a = ' ';" i have receive the same result "I don't understand"
Enoizat (1067)
Hi! the book by Bjarne Stroustrup " The C++ Programming Language" chapter 4.4
Are you entering a number first as what I have done above? I haven't tested it with just by entering a character first. Post your input and output like what I have done above.
fiji885 (235) done! thank you! it was a silly mistake
the book by Bjarne Stroustrup " The C++ Programming Language" chapter 4.4

The original code is a bit clearer than yours ("I don't know a unit called '" << unit << "'" outputs a clearer message):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int main()
{
    constexpr double cm_per_inch = 2.54;    // number of centimeters in an inch
    double length = 1;                      // length in inches or centimeters
    char unit = 'a';
    cout << "Please enter a length followed by a unit (c or i):\n";
    cin >> length >> unit;
    switch (unit) {
    case 'i':
        cout << length << "in == " << cm_per_inch*length << "cm\n";
        break;
    case 'c':
        cout << length << "cm == " << length/cm_per_inch << "in\n";
        break;
    default:
        cout << "Sorry, I don't know a unit called '" << unit << "'\n";
        break;
    }
}


Anyway, the book is “Programming: Principles and Practice Using C++” and the chapter is
4.4.1.2.
Enoizat, thank you!
Topic archived. No new replies allowed.