2016-11-12 54 views
0

我已经写了一些代码,其中的节目信息从文件中读取(这里的文件)改变阵列的载体

5 
Franks,Tom 2 3 8 3 6 3 5 
Gates,Bill 8 8 3 0 8 2 0 
Jordan,Michael 9 10 4 7 0 0 0 
Bush,George 5 6 5 6 5 6 5 
Heinke,Lonnie 7 3 8 7 2 5 7 

,并把它分成两列。一个用于名称,另一个用于数字。然后合计数字并将其存储在数据数组中。现在我需要将所有数组更改为Vectors,并且我很困惑如何做到这一点。我知道我需要使用push_back,但我对如何开始感到困惑。

下面是与数组代码:

int data[50][8]; 
string names[50];  

int const TTL_HRS = 7; 
ifstream fin; 
fin.open("empdata.txt"); 

if (fin.fail()) { 
    cout << "ERROR"; 
} 

int sum = 0; 
int numOfNames; 
fin >> numOfNames; 

for (int i = 0; i < numOfNames; i++) { 

    fin >> names[i]; 

    data[i][7] = 0; 

    for (int j = 0; j < 7; j++) { 
     fin >> data[i][j]; 
     data[i][TTL_HRS] += data[i][j]; 
    } 
} 

fin.close(); 
return numOfNames; 

} 

我知道,我必须使阵列载体。因此,我将有

vector<vector<int>>data; 

vector<string>names; 

,但我不知道如何去填充。

+0

您的C++书至少应该有一章解释向量如何工作以及如何使用它们。我确定它有一个例子展示了如何添加或删除矢量的值。你读过那章了吗? –

回答

0

您可以使用.push_back()方法逐个添加元素。

顺便说一句,我很好奇,为什么你想要矢量而不是数组?

例如,对于您的字符串向量,你可以通过

string tmpString; 
fin >> tmpString; 
names.push_back(tmpString); 

有可能(可能)更好的方式来做到这一点改变fin >> names[i];,但是这就是我看到它。

+0

我正在练习使用矢量,所以我想改变一个代码,我做了数组与一个矢量 – Ralf

+0

好吧,我试图编辑更清楚^ -^ – FeelZoR

+0

好吧我现在正在尝试 – Ralf

0

这看起来挺有意思。但是我建议你将一个C++ 11类似的结构std::array复制到C-array。对于小尺寸和固定尺寸的数据(比如你的样本),它是more efficient比std :: vector。

0

我假设.txt文件中有这样的:

Franks Tom 2 3 8 3 6 3 5 

您的问题,基本解决方案。

int main(int argc, const char * argv[]) { 
     vector <int> numbers; 
     vector <string> names; 
     string line, name1, name2; 
     int num[7]; 


     ifstream fin("/empdata.txt"); 


     if (!fin.is_open()) { 
      cout << "ERROR"; 
     } 
     else{ 

      while(getline(fin, line)){ 
       istringstream is(line); 

       is >> name1; 
       is >> name2; 
       for(int i=0; i<7; i++){ 
        is >> num[i]; 
       } 
       names.push_back(name1); 
       names.push_back(name2); 

       for(int i=0; i<7 ; i++){ 
        numbers.push_back(num[i]); 
       } 

      } 
      fin.close(); 
     } 
     //Printing what did you read from a file 
     string allNames; 
     for(auto it = names.begin(); it < names.end(); it++){ 
      allNames += (*it) + "\t"; 
     } 
     cout << allNames << endl; 

     for (auto it = numbers.begin(); it < numbers.end(); it ++){ 
      cout << (*it) << "\t"; 
     } 

     return 0; 
    }