2016-01-23 92 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