处理空格(或制表符)分隔的文件"like"和数组 - C++
Treat a space(or tab) separated file "like" and array - C++
我有一个简短的文件(我可以相应地创建它),结构为
[data00] <space> [data01] <space> [data02] <space> [data03] <newline>
[data10] <space> [data11] <space> [data12] <space> [data13] <newline>
...
表示数字ID的第一列。我创建这个文件是为了将它提供给另一个可执行文件,所以格式是固定的。在输入它之后,可执行文件输出另一个具有类似结构的文件:
[data00] <space> [data01]<newline>
[data10] <space> [data11]<newline>
...
给定一个ID,我需要读取相应的[dataX1]
,在第一个文件中对[dataX3]
执行操作,将其反馈给可执行文件,并迭代。
我想到了两种方法:
- 操作两个文本文件"好像"它们是数组,因为它们的结构是固定的,但我失去了使用什么函数/语法。这应该是一个小函数,允许我通过传递相关的数字ID来读取有趣的位,隐藏所有讨厌的I/O代码,因为我可能需要在不同的上下文中重复这个操作很多
- 将第一个文件保存在数组中,并通过向可执行文件提供流来欺骗它(这可能吗?
我可以很容易地将文件读入数组并每次重新写入文件,但是我想避免无用的读写操作,当我每次只需要读/写一个单元格时。我现在不知道如何做的是,当我使用getline
从文本文件中读取整行时,如何停止/识别感兴趣的位。
首先,我们将编写一个函数,根据给定的分隔符拆分输入的字符串。(在这种情况下,我们将使用空格。)
int split(const std::string& line, const std::string& seperator, std::vector<std::string> * values){
std::string tString = "";
unsigned counter = 0;
for(unsigned l = 0; l < line.size(); ++l){
for(unsigned i = 0; i < seperator.size(); ++i){
if(line[l+i]==seperator[i]){
if(i==seperator.size()-1){
values->push_back(tString);
tString = "";
++counter;
}else continue;
}else{
tString.push_back(line[l]);
break;
}
}
}
return counter;
}
现在我们将自己编写一个简单的main来读取文件,使用split将其分解,然后根据其在文件中的位置输出数据。
int main(){
std::vector<std::vector<std::string> > lines;
std::string tString = "";
std::vector<std::string> tVector;
std::ifstream fileToLoad;
fileToLoad.open(FILE_NAME);
if(fileToLoad.is_open()){
while(std::getline(fileToLoad,tString)){
split(tString, " ", &tVector);
lines.push_back(tVector);
tVector.clear();
}
//Now print our output.
for(unsigned i1 = 0; i1 < lines.size(); ++i1){
for(unsigned i2 = 0; i2 < lines[i1].size(); ++i2){
std::cout<<"["<<i1<<","<<i2<<"] = "<<lines[i1][i2]<<std::endl;
}
}
}else{
std::cerr<<"FAILED TO OPEN FILE: "<<FILE_NAME<<std::endl;
return 1;
}
return 0;
}
我使用的输入文件包含以下数据:
450 105 10 10.5 -10.56001 23
10 478 1290 384 1289 3489234 1 2 3 4 5
1 2 3 4 5 6.1 19 -1.5
输出:
[0,0] = 450
[0,1] = 105
[0,2] = 10
[0,3] = 10.5
[0,4] = -10.56001
[1,0] = 10
[1,1] = 478
[1,2] = 1290
[1,3] = 384
[1,4] = 1289
[1,5] = 3489234
[1,6] = 1
[1,7] = 2
[1,8] = 3
[1,9] = 4
[2,0] = 1
[2,1] = 2
[2,2] = 3
[2,3] = 4
[2,4] = 5
[2,5] = 6.1
[2,6] = 19
现在您需要做的就是使用您喜欢的解析算法将每个字符串更改为双精度类型。(strtod, atof等)根据优化的重要性,您可能还需要从vector修改容器,这取决于您的用例。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '