提示输入太多次也会导致阵列输出出现问题

时间:2012-12-17 12:29:31

标签: c++

好吧,我的assignment希望我从用户那里获得有关公司4个部门的信息。当我运行并编译它时,它会提示8个分区(就像我说的,我只想要4个),当它显示收集到屏幕上的信息时,它不显示不同分区的名称。 Example

#include<iostream>
#include<cstdlib>
#include<fstream>
#include<sstream>
#include <vector>

using namespace std;

const int SIZE = 12;

struct Division
{
      char divName[SIZE]; // Division name
      double sales[4]; // Quarterly sales stored as an array
};



int main()
{
       void Intro();
       std::vector<Division> CreateCorporateFile();
       void DisplayCorporateSales();

       Intro();
       CreateCorporateFile();
       DisplayCorporateSales();


       system("PAUSE");
       return 0;
}

void Intro()
{
     cout<<"This program will prompt you to enter in quarterly sales for "
           "four different\ndivisions of a company.\n\n";
}


std::vector<Division> CreateCorporateFile()
{
    std::vector<Division> divArray;
    Division div;
    int x = 0;
    for(int x = 0; x < 4; x++)
    {
    /*do {*/int quarter = 1;
          cout << "Enter the name of the division: ";
          cin >> div.divName;
          for(int i = 0; i < 4; i++)
          {
               cout << "Enter in the sales for quarter "<< quarter <<": ";
               cin >> div.sales[i];
               if(div.sales[i] > 0)
               {
                    quarter++;
               }
               else
               {
                    cout << "Sales are not allowed to be negative.\n";
               }
          }

        divArray.push_back(div);
        /*x++;
    } while(x < 4);*/
}
    return divArray;
}




void DisplayCorporateSales()
{
     Division div;

         std::vector<Division> divisions = CreateCorporateFile();
    for (size_t i=0; i<divisions.size(); i++)
    {
        cout << "Here are the quarterly sales for " << div.divName
        << ": \n";
        Division div = divisions[i];
        for(int j = 0, quarter = 1; j < 4; ++j, ++quarter)
        {
            cout << "Quarter "<< quarter << " sales: $"<< div.sales[j]
            <<"\n";
        }
    }         
}

1 个答案:

答案 0 :(得分:3)

它要求加倍的原因是因为你两次致电CreateCorporateFile

仅在main中调用它,保存返回的向量,并将其传递给DisplayCorporateSales根本不在main中调用它。

我还建议您使用std::string作为字符串(名称)而不是char数组。