从输入文件中读取多行

Reading multiple lines from an input file

我有一个包含多行(数组)int 的输入文件。我不知道如何分别读取每个数组。我可以读取所有 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,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] == ',' || str[i] == ']') 
          {
              // the commma and end bracket 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