2013-12-11 111 views
0

我想將一個變量設置爲二維數組元素的值。這應該很容易,但是每當我寫它時,我都會在變量中得到0。我在一個文件中讀入手動添加數組元素,這可能會導致問題,但我不確定是什麼錯誤。表操作錯誤

這是我的代碼:

int main(){ 

//declaring all the variables 
vector < vector <double> > data; // vector of vectors to hold the data. 
int z=0; 
int z1,z2; 
//open the input file as an input file stream (ifstream) 
    ifstream dataFile; 
    dataFile.open("GBplaces.csv"); 

    //if the file is open... 
    if (dataFile.is_open()) { 

    // and while it's not the end of the file... 

     while (!dataFile.eof()){ 
      z++; 
      if (z==1){ 
      string aLine; 
      getline (dataFile, aLine); 
      printf ("place, type, population, lattitude, longitude \n\n"); 
      } 

      else if(z==102){ 
      string aLine; 
      getline (dataFile, aLine); 
      } 

      else { 

     //read in a line of the file and put the ontents into the arays. 

     string aLine; // hold the read in line 

     getline (dataFile, aLine); //reads line from dataFile to aLine 

     //split up the string aLine based on where the comma is 
     int comma; 
     int nextCom=0; 
     //comma_pos = aLine.find(',',0); //finds where the comma is, starting from the begining ie 0 

     string xst, yst, zst; //temp variables for column 
     vector <double> temp; // tempory vector for the points 
     double xt, yt, zt; 

     comma = aLine.find(',',0); //find first position of comma 
     xst = aLine.substr(0,comma); // extracts string subvalue 
     temp.push_back(atof(xst.c_str())); //add value to end of temporary vector 
     comma += 1; // add 1 to the comma position count 

    while (aLine.find(',',comma) != -1) { 
     // find middle values 
     if(aLine==""){} 
     else{ 
     nextCom = aLine.find(',',comma); 
     yst = aLine.substr(comma, nextCom - comma); 
     temp.push_back(atof(yst.c_str())); //convert string into double and add it to the end of the vector 
     comma = nextCom + 1; 
     } 
    } 
    // same calculations as in the loop but for the last value after the comma 
    zst = aLine.substr(nextCom + 1, aLine.length()); 
    temp.push_back(atof(zst.c_str())); 


     // push temporary vector onto data vector 
     data.push_back(temp);  
     } 
     } 
    } 

Z =數據[3] [3]。

當我運行程序時,我得到z = 0,但是當我打印表格時,元素是51.26。

+0

這:'while(!dataFile.eof())'幾乎肯定是一個問題。 [閱讀此爲什麼](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong)。這在任何一個字面上都沒有*錯誤檢查,並不能完全幫助你。 – WhozCraig

+0

非常感謝,請關注! – Dimitris

回答

0

更新:

發現錯誤:

int z=0; 
int z1,z2; 

Z1,Z2應該是雙打,而不是整數。這是搞亂了其餘的數字