[英]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的每一行作为多维向量访问 。 或者,如果您的目标是在数据中存储所有整数的一个向量,则输入流循环应为
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的好方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.