janac

Fill array based on user input

Nov 23rd, 2021 (edited)
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.41 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4. using namespace std;
  5.  
  6. // Fill an array with fruit or vegetable
  7. // words, depending on user input.
  8. int main()
  9. {
  10.     vector<string> basket; // List of foods.
  11.     string choice; // User input.
  12.    
  13.     cout << "Do you want a basket of fruit or vegetables?\n";
  14.     cin >> choice; // Get the user's choice.
  15.  
  16.     // If the user didn't choice fruit or vegetables.
  17.     if ( (choice.compare("fruit") != 0) && (choice.compare("vegetables") != 0) )
  18.     {
  19.         // Inform the user their choice isn't available.
  20.         cout << "I'm sorry, we don't have " << choice << ".\n";
  21.     }
  22.     else // Otherwise, if the user chose fruit or vegetables,
  23.     {
  24.         // If the user chose fruit,
  25.         if (choice.compare("fruit") == 0)
  26.         {
  27.             // Add fruit words to the list.
  28.             basket.push_back("apple");
  29.             basket.push_back("orange");
  30.             basket.push_back("banana");
  31.             basket.push_back("plum");
  32.         }
  33.         // Otherwise, if the user chose vegetables,
  34.         else if (choice.compare("vegetables") == 0)
  35.         {
  36.             // Add vegetable words to the list.
  37.             basket.push_back("spinach");
  38.             basket.push_back("carrots");
  39.             basket.push_back("cauliflower");
  40.             basket.push_back("broccoli");
  41.         }
  42.  
  43.         cout << "Here's your basket:\n";
  44.        
  45.         // Display the basket.
  46.         for (string food : basket) // For each item,
  47.         {
  48.             cout << food << '\n'; // Display it.
  49.         }
  50.  
  51.         cout << "\nHave a nice day!\n";    
  52.     }
  53.  
  54.     // End the program.
  55.     return 0;
  56. }
Add Comment
Please, Sign In to add comment