if else...

Hi there

Just want to check,
I was playing with code (please see below), and one thing I was not sure about why if I had just if rather then else if when correct choice was made it still
executed (last) else statement.

why?

thanks :)

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
#include <iostream>
#include <string>

int main()
{
	while (true)
	{
		std::cout << "Please type number: ";
		std::string number = " ";
		std::cin >> number;
		
		if (number == "zero" || number == "Zero" || number == "ZERO")
		{
			std::cout << "Number entered is 0" << std::endl;
		}
		else if (number == "one" || number == "One" || number == "ONE")
		{
			std::cout << "Number entered is 1" << std::endl;
		}
		else if (number == "two" || number == "Two" || number == "TWO")
		{
			std::cout << "Number entered is 2" << std::endl;
		}
		else if (number == "three" || number == "Three" || number == "THREE")
		{
			std::cout << "Number entered is 3" << std::endl;
		}
		else if (number == "four" || number == "Four" || number == "FOUR")
		{
			std::cout << "Number entered is 4" << std::endl;
		}
		else (std::cout << "I am sorry I don't recognise this.... try again would you?" << std::endl);
		
	}

    return 0;
}
Last edited on
why?

Please show the code that is confusing you. This code only prints the "error message" when it should.


By the way, why are you accepting four, Four, or FOUR but not FOur or any of the other combinations. Wouldn't it be better to just do a case insensitive check instead?

Hi jib

yes, that is correct, if you replace else if with just if then it prints correct part of the code and else statement.
I was not sure why is that happening?

I did't do all possible combinations/case sensitive because that was not an assignment.
I am following book Bjarne Stroustrup Programming principles and practise using C++.

thanks for the reply :)
if you replace else if with just if then it prints correct part of the code and else statement

Hi, @xxvms
as far as I can see it’s what it should do, it’s not?

If you enter let's say “three”, then:
is it “zero”? --> no, let’s go on
is it “one”? --> no, let’s go on
is it “two”? --> no, let’s go on
is it “three”? --> yes! Let’s print “Number entered is 3”
is it “four”? --> no, let’s execute the “else” statement:
print out: “I am sorry I don't recognise...”

Did I misunderstood your question?

BTW:
std::string number = " ";
strings are objects, so they’re initialized in the constructor as empty strings when they are not assigned a value. I mean, they start in a consistent state anyway.
Topic archived. No new replies allowed.