Home > Software engineering >  Stuck on if else nested loop, complex question
Stuck on if else nested loop, complex question

Time:09-24

Hi all have been programming for a little more than 6 months, still working on it and trying new things. I had a questions involving my program.

Here is my source code, I am trying to create a nested if else that includes everything that is on there but if the user inputs something other than a month it will say

ELSE { cout << "Not a valid input." << endl;

However, I am having difficulties doing this. Any help would be appreciated!!!

#include <iostream>
#include <string>
using namespace std;

int main() {
   string inputMonth;
   int inputDay;
   
    cout << "Enter a month and date (example March 3) :";
   
   cin >> inputMonth;
   cin >> inputDay;
   
   
   if (inputMonth == "January" || inputMonth == "january") {
      if ((inputDay < 31) || (inputDay > 0)) 
         cout << "Winter";
      }
   else if (inputMonth == "February" || inputMonth == "february") {
      if ((inputDay <= 29) || (inputDay > 0))
      cout << "Winter";
   }
   else if (inputMonth == "March" || inputMonth == "march") {
       if ((inputDay < 20) && (inputDay > 0)){
       cout << "Winter";
   }
       else { (inputDay < 31 && inputDay > 20);
       cout << "Spring";
   }
   }
   else if (inputMonth == "April" || inputMonth == "april") {
      if ((inputDay > 0) || (inputDay < 31))
      cout << "Spring";
   }
   else if (inputMonth == "May" || inputMonth == "may") {
      if ((inputDay > 0) || (inputDay < 32)) 
      cout << "Spring";
   }
   else if (inputMonth == "June" || inputMonth == "june") {
      if (inputDay < 20 && inputDay >= 0) {
      cout << "Spring";
      }
      else if (inputDay == 25) {
      cout << "Alaya's birthday";
  }
      else { ((inputDay > 20) && (inputDay < 31)) ;
      cout << "Summer";
   }
   }
   else if (inputMonth == "July" || inputMonth == "july") {
       if (inputDay > 0 && inputDay < 32) {
           cout << "Summer";
       }
       else if (inputDay == 6) {
           cout << "Sabrina's birthday";
       }
   }
   else if (inputMonth == "August" || inputMonth == "august") {
      if  (inputDay == 3) {
      cout << "Andre and Nicolle's birthday ";
      }
      else {  ((inputDay > 0) && (inputDay < 32));
      cout << "Summer";
      }
   }
   else if (inputMonth == "September" || inputMonth == "september") {
       if (inputDay > 0 && inputDay < 22) {
           cout << "Summer";
       }
       else { (inputDay > 23 && inputDay < 31);
       cout << "Autumn";
   }
   }
   else if (inputMonth == "October" || inputMonth == "october") {
       if (inputDay > 0 && inputDay < 31) 
       cout << "Autumn";
   }
   else if (inputMonth == "November" || inputMonth == "november") {
       if (inputDay > 0 && inputDay < 31) 
       cout << "Autumn";
   }
   else if (inputMonth == "December" || inputMonth == "december") {
       if (inputDay > 0 && inputDay < 21) {
           cout << "Autumn ";
       }
       if (inputDay == 4) {
           cout << "Gina's birthday";
       }
       else if (inputDay == 20) {
           cout << "Cely's birthday";
       }
        else if (inputDay > 21 && inputDay < 32) {
           cout << "Winter";
       }
       else if (inputDay == 23) {
           cout << "Bobbys birthday";
       } 
    // Intended and tried to put an else statement here but would not work.
   }
   return 0;
}

CodePudding user response:

your code does what you want as follows, but I definitely don't recommend this method. I just tried to help without breaking the structure of your code. Why do I not recommend this method because you would be reading a variable that could take hundreds of values, not months, as input, and it is impossible to write it one by one for all of them. That's why I only provided you with a solution without breaking the general structure of your code, but as I said, you should improve yourself. Note : I changed the name of the inputMonthvariable to im.

#include <iostream>
#include <string>
using namespace std;

int main() {
    string im;
    int inputDay;

    cout << "Enter a month and date (example March 3) :";

    cin >> im;
    cin >> inputDay;

    while (std::cin.fail() || (im != "January " && im != "january" && im != "February" && im != "february" && im != "March" && im != "march" && im != "April" && im != "april" && im != "May" && im != "may" && im != "June" && im != "june" && im != "July" && im != "july" && im != "August" && im != "august" && im != "September" && im != "september" && im != "October" && im != "october" && im != "November" && im != "november" && im != "December" && im != "december")) {
        std::cout << "Error! Not a valid input.\n";
        std::cin.clear();
        std::cin.ignore(256, '\n');
        std::cout << "Enter a month and date (example March 3) ";
        cin >> im;
        cin >> inputDay;
    }

    if (im == "January" || im == "january") {
        if ((inputDay < 31) || (inputDay > 0))
            cout << "Winter";
    }
    else if (im == "February" || im == "february") {
        if ((inputDay <= 29) || (inputDay > 0))
            cout << "Winter";
    }
    else if (im == "March" || im == "march") {
        if ((inputDay < 20) && (inputDay > 0)) {
            cout << "Winter";
        }
        else {
            (inputDay < 31 && inputDay > 20);
            cout << "Spring";
        }
    }
    else if (im == "April" || im == "april") {
        if ((inputDay > 0) || (inputDay < 31))
            cout << "Spring";
    }
    else if (im == "May" || im == "may") {
        if ((inputDay > 0) || (inputDay < 32))
            cout << "Spring";
    }
    else if (im == "June" || im == "june") {
        if (inputDay < 20 && inputDay >= 0) {
            cout << "Spring";
        }
        else if (inputDay == 25) {
            cout << "Alaya's birthday";
        }
        else {
            ((inputDay > 20) && (inputDay < 31));
            cout << "Summer";
        }
    }
    else if (im == "July" || im == "july") {
        if (inputDay > 0 && inputDay < 32) {
            cout << "Summer";
        }
        else if (inputDay == 6) {
            cout << "Sabrina's birthday";
        }
    }
    else if (im == "August" || im == "august") {
        if (inputDay == 3) {
            cout << "Andre and Nicolle's birthday ";
        }
        else {
            ((inputDay > 0) && (inputDay < 32));
            cout << "Summer";
        }
    }
    else if (im == "September" || im == "september") {
        if (inputDay > 0 && inputDay < 22) {
            cout << "Summer";
        }
        else {
            (inputDay > 23 && inputDay < 31);
            cout << "Autumn";
        }
    }
    else if (im == "October" || im == "october") {
        if (inputDay > 0 && inputDay < 31)
            cout << "Autumn";
    }
    else if (im == "November" || im == "november") {
        if (inputDay > 0 && inputDay < 31)
            cout << "Autumn";
    }
    else if (im == "December" || im == "december") {
        if (inputDay > 0 && inputDay < 21) {
            cout << "Autumn ";
        }
        if (inputDay == 4) {
            cout << "Gina's birthday";
        }
        else if (inputDay == 20) {
            cout << "Cely's birthday";
        }
        else if (inputDay > 21 && inputDay < 32) {
            cout << "Winter";
        }
        else if (inputDay == 23) {
            cout << "Bobbys birthday";
        }
        
    }
    return 0;
}

CodePudding user response:

Even though this looks radically different than your original code, you could remove all of the nested if statements, thus the if statement you want to add (invalid input) makes the job easier.

The approach illustrated uses concepts you should pick up, even if you're a beginner.

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <cctype>

struct seasonInfo
{
    std::string name;
    int startDay;
    int endDay;
};

struct birthdayInfo
{
    std::string name;
    int day;
};

struct monthInfo
{
    std::string name;
    int startDay;
    int endDay;
    std::vector<seasonInfo> seasons;
    std::vector<birthdayInfo> birthdays;
};

int main()
{
    // Season table
    std::vector<seasonInfo> janseason = { { "Winter", 1, 31 } };
    std::vector<seasonInfo> febseason = { { "Winter", 1, 28 } };
    std::vector<seasonInfo> marchseasons = { { "Winter", 1, 20 }, { "Spring", 21, 31 } };
    std::vector<seasonInfo> aprilseason = { { "Spring", 1, 30 } };
    std::vector<seasonInfo> mayseason = { { "Spring", 1, 31 } };
    std::vector<seasonInfo> juneseasons = { { "Spring", 1, 20 },{ "Summer", 21, 30 } };
    std::vector<seasonInfo> julyseason = { { "Summer", 1, 31 } };
    std::vector<seasonInfo> augustseason = { { "Summer", 1, 31 } };
    std::vector<seasonInfo> septemberseasons = { { "Summer", 1, 20 },{ "Autumn", 21, 30 } };
    std::vector<seasonInfo> octoberseason = { { "Autumn", 1, 31 } };
    std::vector<seasonInfo> novemberseason = { { "Autumn", 1, 30 } };
    std::vector<seasonInfo> decemberseasons = { {"Autumn", 1, 20 },{ "Winter", 21, 31 } };

    // birthday info
    std::vector<birthdayInfo> junebirthday = { { "Alaya's", 25 } };
    std::vector<birthdayInfo> julybirthday = { { "Sabrina's", 6 } };
    std::vector<birthdayInfo> augustbirthday = { { "Andre and Nicolle's", 3 } };
    std::vector<birthdayInfo> decemberbirthdays = { { "Gina's", 4 }, { "Cely's", 20 }, { "Bobby's", 20 } };

    // combination of the season info, birthday, and other month information
    std::vector<monthInfo> allMonths = { { "january", 1,31, janseason,{} },
                                            { "february", 1,28, febseason,{} },
                                            { "march", 1,31, marchseasons,{} },
                                            { "april", 1,30, aprilseason,{} },
                                            { "may", 1,31, mayseason,{} },
                                            { "june", 1,30, juneseasons,junebirthday },
                                            { "july", 1,31, julyseason,julybirthday },
                                            { "august", 1,31, augustseason,augustbirthday },
                                            { "september", 1,30, septemberseasons,{} },
                                            { "october", 1,31, octoberseason,{} },
                                            { "november", 1,30, novemberseason,{} },
                                            { "december", 1,31, decemberseasons,decemberbirthdays } };

    // a map of the month name and all the information associated with that month
    std::map<std::string, monthInfo> table;

    // build the map elements
    for (int i = 0; i < 12;   i)
        table[allMonths[i].name] = allMonths[i];

    // start.
    std::string inputMonth;
    int inputDay;

    std::cout << "Enter a month and date (example March 3) :";
    std::cin >> inputMonth;
    std::cin >> inputDay;

    // make all lower case
    for (auto& ch : inputMonth)
        ch = static_cast<unsigned char>(std::tolower(ch));

    // Note that *none* of the code below needs to be changed if more birthdays are added.  Just
    // add the birthday to the table above if there will be more
    
    bool foundSeason = false;
    // Look up the month
    auto iter = table.find(inputMonth);
    if (iter != table.end())
    {
        // Output the season based on the day
        auto& seasons = iter->second.seasons;
        for (size_t i = 0; i < seasons.size();   i)
        {
            if (inputDay >= seasons[i].startDay && inputDay <= seasons[i].endDay)
            {
                foundSeason = true;
                std::cout << seasons[i].name << "\n";
                break;
            }
        }

        if (foundSeason)
        {
            // Output the birthdays based on the day
            auto& birthdays = iter->second.birthdays;
            for (size_t i = 0; i < birthdays.size();   i)
            {
                if (birthdays[i].day == inputDay)
                    std::cout << birthdays[i].name << " birthday" << "\n";
            }
        }
    }
    if ( !foundSeason )
        std::cout << "Not a valid input" << "\n";
}

I will admit, even this is probably not the most optimal approach, but it is here to illustrate a point.

The point being that if you can create a table of the information beforehand, and in the body of the code, somehow "point" to the information block you're interested in, the code not only becomes easier to maintain, but extensible (if you are a beginner learning a language like JavaScript, this should look a little similar to how you set this up in a language like that).

If you look at the code above, all the information concerning season information, birthday information, and month information are stored in separate struct's (again, read up on what structs are, as they are basic building blocks of learning C ).

Note also the usage of std::vector, which is a dynamic array class of C . Another item to look up and study.


Given that, if you knew very little about C , if you take a look at the main function and the comment // Season table, you will see the table being built out. We define the season information for each month, we define the birthday information for each month.

Then we collate all of that information into a dynamic array (a vector) of month information. If you take a look at allMonths, the information is built right before your eyes (conceptually) -- even a novice C programmer should get the idea of what's going on conceptually, even though the syntax may be a little bit hard to grasp at first.

The last step is to add all this information into a lookup map, where we use the month name to lookup the information we are seeking.

Again, this is somewhat advanced since you are not aware of the syntax being used, etc. But at first glance, you see how the table is being built conceptually.

In addition, if you were to add birthdays, or for some strange reason, add months, change days, etc., you do it all in the table above -- you never need to add or change a single line of code after where you get the input.

The logic to search the information, i.e. match the day with the seasons and output the birthday information -- that should be simple enough to figure out (not the best way to do it, but a simple loop through the season information to find the season).


Last but not least, that if statement that was giving you trouble -- take a look at the last line of main. Nothing could get more simpler than that. If we input a bad month, or the day doesn't match any seasonal day for the matching month, it is bad input.

CodePudding user response:

not difficult at all

just add

else{
   cout << "Not a valid input." << endl;
}
  •  Tags:  
  • c
  • Related