【问题标题】:Reading multiple lines from an input file从输入文件中读取多行
【发布时间】:2016-01-23 04:51:42
【问题描述】:

我有一个包含ints 的多行(数组)的输入文件。我不知道如何分别读取每个数组。我可以读取所有ints 并将它们存储到一个数组中,但我不知道如何分别从输入文件中读取每个数组。理想情况下,我想通过不同的算法运行数组并获得它们的执行时间。

我的输入文件:

[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 函数来检查是否有括号,然后在那里结束吗?如果这样做,我如何告诉程序从下一个左括号开始读取并将其存储在新向量中?

【问题讨论】:

    标签: c++ arrays ifstream


    【解决方案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] == ',' || 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的好方法。

    【讨论】:

    • 唯一的问题是有时数组会占用多行。所以我可能有 20 多个 int 将结束到下一行。
    • @shelum 您的编辑器设置为使用自动换行吗?如果是,则将其设置为不。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多