else not working

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
#include <iostream>
#include <string>
int main()
{
using namespace std;
string today;
cout << "What day of the week is it? ";
cin >> today;
if (today == "Sunday")
cout << "today is Sunday";
if (today == "Monday")
cout << "today is Monday";
if (today == "Tuesday")
cout << "today is Tueday";
if (today == "Wednesday")
cout << "today is Wednesday";
if (today == "Thursday")
cout << "today is Thursday";
if (today == "Friday")
cout << "today is Friday";
if (today == "Saturday")
cout << "today is Saturday";
else
cout << "you have entered the wrong input, please try again";
}

Why does it mesh a day of the week if today is true?
You need a multiway if statement, try this:

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
#include <iostream>
#include <string>
using namespace std;

int main(){
	string today;
	
	cout << "What day of the week is it?" << endl;
	
	cin >> today;
	
	if (today == "Sunday")
		cout << "today is Sunday";
	else if (today == "Monday")
		cout << "today is Monday";
	else if (today == "Tuesday")
		cout << "today is Tueday";
	else if (today == "Wednesday")
		cout << "today is Wednesday";
	else if (today == "Thursday")
		cout << "today is Thursday";
	else if (today == "Friday")
		cout << "today is Friday";
	else if (today == "Saturday")
		cout << "today is Saturday";
	else
		cout << "you have entered the wrong input, please try again";

	
	return 0;
}
 


Here's my guess as to what happened:

In your example there are a bunch of ifs and one else. The else "links" itself with one of the ifs (say Saturday). So when you enter a valid day (say monday), one of the if conditions is fulfilled, HOWEVER, when it checks for saturday, the condition is not fulfilled, so it automatically goes to the else.

In the multiway if statement, the else is only ever executed when all of the other ifs are not fulfilled.

I think.
Last edited on
i am confused at why this works
i am very early in learning c++, is this something i missed learning or is it something deeper in that i will learn later?
Last edited on
No problemo, my guess as to what happened it edited in.
ah ok thanks
Topic archived. No new replies allowed.