'Beginner C++ Beverage Survey Tally

I am working on an assignment that is supposed to perform a survey tally on people's favorite beverages. Ideally it will continue asking the user to submit a favorite beverage for each individual they wish to include. When the user is done casting all of the votes, he or she enters -1 and the count should be displayed. The only problem I am noticing is that when the results are printed out, I get arbitrarily large numbers for each beverage. I am still very new to coding and even newer to C++, but does it have to do with the scope of the switch statement? It doesn't appear to be adding to the count of the beverages at all :/.

#include <iostream>
#include <stdlib.h>

using namespace std;

int main()
{
    int input, vcoff, vtea, vcoke, voj, personNumber = 1;

     cout << "Welcome to the favorite beverage survey. Our beverage options are: "<< endl;
     cout << "1.Coffee   2.Tea   3.Coke   4.Orange Juice" << endl;
     cout << endl;
     cout << "Please input the favorite beverage of person # " << personNumber << ": Choose 1, 2, 3, or 4 from the"<< endl << "above menu or -1 to exit the program."<< endl;
     cin >> input;

  while (input < -1)
  {
    cout << "That is not an option. Please reenter a valid number: " << endl;
    cin >> input;
  } 

  while (input > 0)
  {
    switch(input)
    {
    case 1: vcoff++;
    break;
    case 2: vtea++;
    break;
    case 3: vcoke++;
    break;
    case 4: voj++;
    break;
    default: cout << "Sorry, that's not a menu item. Please try again: " << endl;
    cin >> input;
    }
    personNumber++;
     cout << "Please input the favorite beverage of person # " << personNumber << ": Choose 1, 2, 3, or 4 from the"<< endl << "above menu or -1 to exit the program."<< endl;
     cin >> input;
  } 

 if (input = -1)
 {
   cout << "The total number of people surveyed is " << personNumber << ". The results are as follows:" << endl;
   cout << "Beverages     Votes" << endl << "**********************" << endl;
   cout << "Coffee:    " << vcoff << endl;
   cout << "Tea:    " << vtea << endl;
   cout << "Coke:    " << vcoke << endl;
   cout << "Orange Juice:    " << voj << endl;
 }

return 0;
}
c++


Solution 1:[1]

You missed the initialisation of the variables. Local variables are not initialised to 0 if you don't tell so.

This means that the starting value can be any unpredicatable value, which explains that you find weird numbers.

Try:

int input=0, vcoff=0, vtea=0, vcoke=0, voj=0, personNumber = 1;

Solution 2:[2]

Instead of int input, vcoff, vtea, vcoke, voj, personNumber = 1; Do int input = 0, vcoff = 0, vtea = 0, vcoke = 0, voj = 0, personNumber = 1; to initialise the variables.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Christophe
Solution 2 SegFault