2016-01-23 96 views
0

我有一個輸入文件,其中有多行(數組)int s。我不知道如何分別讀取每個數組。我可以讀取所有的int並將它們存儲到單個數組中,但我不知道如何從輸入文件中單獨讀取每個數組。理想情況下,我想通過不同的算法運行數組,並獲得執行時間。從輸入文件讀取多行

我的輸入文件:

[1, 2, 3, 4, 5] 
[6, 22, 30, 12 
[66, 50, 10] 

輸入流:

ifstream inputfile; 
inputfile.open("MSS_Problems.txt"); 
string inputstring; 
vector<int> values; 

while(!inputfile.eof()){ 
     inputfile >> inputstring; 
     values.push_back(convert(inputstring)); 
} 
inputfile.close(); 

轉換功能:

for(int i=0; i<length; ++i){ 
    if(str[i] == '['){ 
     str[i] = ' '; 
    }else if(str[i] == ','){ 
     str[i] = ' '; 
    }else if(str[i] == ']'){ 
     str[i] = ' '; 
    } 
} 
return atoi(str.c_str()); 

我應該建立一個bool函數來檢查是否有括號,然後在那裏結束?如果我這樣做,我該如何讓程序開始閱讀下一個左括號並將其存儲在新的向量中?

回答

1

也許這就是你想要的?

數據

[1,2,3,4,5] 
[6,22,30,12] 
[66,50,10] 

輸入流:

std::ifstream inputfile; 
inputfile.open("MSS_Problems.txt"); 
std::string inputstring; 
std::vector<std::vector<int>> values; 

while(!inputfile.eof()){ 
     inputfile >> inputstring; 
     values.push_back(convert(inputstring)); 
} 
inputfile.close(); 

轉換功能:

std::vector<int> convert(std::string s){ 
     std::vector<int> ret; 
     std::string val; 
     for(int i = 0; i < s.length; i++){ 
      /*include <cctype> to use isdigit */ 
      if(std::isdigit(str[i])) 
      val.push_back(str[i]); //or val += str[i]; 
      if(str[i] == ',') 
      { 
       // the commma tells us we are at the end of our value 
      ret.push_back(std::atoi(val.c_str())); //so get the int 
      val.clear(); //and reset our value. 
      } 
     } 
     return ret; 
} 

std::isdigit是一個有用的功能,可以讓我們知道,我們正在尋找的性格數字或不是,所以你可以放心地忽略你的括號。

因此,您將訪問int的每一行作爲multidemensional vector。或者,如果你的目標是讓存儲在數據中的所有整數中的一個載體,然後你的輸入流回路應

vector<int> values; 

while(!inputfile.eof()){ 
     inputfile >> inputstring; 
     std::vector<int> line = convert(inputstring); 
     //copy to back inserter requires including both <iterator> and <algorithm> 
     std::copy(line.begin(),line.end(),std::back_inserter(values)); 
} 
inputfile.close(); 

這是學習使用Copy to back_inserter的好辦法。

+0

唯一的問題是有時數組會佔用多行。所以我可能會有20+個int,它會包裝到下一行。 – shelum

+0

@shelum是你的編輯器設置爲使用自動換行?如果是這樣,那麼就不要這樣做。 – Johnathon