Hi everyone, I'm an absolute beginner here and I'm trying to learn C++ by myself through videos on youtube and other online resources. Here's a small program I practice using loop but somehow it doesn't work out as expected.
#include <iostream>
usingnamespace std;
int main()
{
cout << "What is today's day?" << endl;
cout << " m for Monday \n t for Tuesday \n w for Wednesday \n T for Thursday \n f for Friday \n s for Saturday \n S for Sunday." << endl;
for(char input ; !(input == 'e') ; cin >> input){
switch(input){
case'm':
cout << "It's Monday!" << endl;
break;
case't':
cout << "It's Tuesday!" << endl;
break;
case'w':
cout << "It's Wednesday!" << endl;
break;
case'T':
cout << "It's Thursday!" << endl;
break;
case'f':
cout << "It's Friday!" << endl;
break;
case's':
cout << "It's Saturday!" << endl;
break;
case'S':
cout << "It's Sunday!" << endl;
break;
//Everything else except for 'e' and 7 cases above
default:
cout << "Your input is not valid" << endl;
}
}
//If enter 'e' program will end by displaying this message.
cout << "Have a nice day!";
}
What I'm trying to do is to ask a user to input a character represent the day of the week. Everything works just fine. The problem is that when I build and run the program, it automatically displays "It's Tuesday!" before I enter any character. I also try with 'if' and 'while', but 'for' is a better suit. I've been revising my code many times but still couldn't figure out why. Any help will be appreciated. Thanks in advance.
your code for(char input ; !(input == 'e') ; cin >> input)
your input is tying to do something without knowing what the input is, therefor input something before you do something with it so for(char input ; cin >> input,!(input == 'e') ; )
So if I don't set variable equal to something, then it will automatically get a random value? I thought that the middle section of the for loop is for condition, does that mean that cin >> input is a condition? Thank you.
So if I don't set variable equal to something, then it will automatically get a random value? I thought that the middle section of the for loop is for condition, does that mean that cin >> input is a condition? Thank you.
Yes std::cin >> can be used for a condition such as
1 2 3 4 5 6 7 8 9 10 11
int i = 0
// Make sure we get input
if (std::cin >> i) {
.....
}
// Keep getting input into i
while (std::cin >> I) {}
// declare i2 and initialise it to 0, get input into it and add one to it
for (int i2 = 0; std::cin >> i2; ++i2) {...}