如何在C++中从文本文件中提取数据到并行数组?

问题描述 投票:0回答:1

我有一个文本文件,格式为

(3,8);32
(6,2);57
(2,5);193
(9,4);2921

文本文件中的行数是未知的,可以持续很长时间。我的程序的另一部分是一个地图,由符号组成,存储在一个2D数组中。上面提到的这个文本文件是.NET的。

(row,column) ;price

我需要存储每个变量,以便我可以在2D数组中访问它。我想使用3个并行数组。我的代码如下,但有缺陷。任何帮助将被感激。谢谢你的帮助。

#include <iostream>
#include <fstream>
#include <sstream>
#include <String>
using namespace std;
int main ()
{
string line;
sstream sr;
int aRow[];   //not sure how to declare as number of lines in textfile is unknown
int aCol[];   //not sure how to declare as number of lines in textfile is unknown
int aPrice[]; //not sure how to declare as number of lines in textfile is unknown
ifstream inputfile;
inputfile.open("file.txt");
while (inputfile)
{
arow[] = line[1];
acol[] = line[2];
aprice[] = //everything after semicolon

}
return 0;
}

c++ arrays string parallel-processing text-files
1个回答
0
投票

如果你想要一个 "一些未知行数 "的数组,你真正想要的是一个 std::vector<int>. 然后你就可以 v.push_back(an_int) 每一行,然后向量就会增长以适应它们。 如果你需要将它们作为一个老式数组传递,你可以将一个指向它们的指针作为 v.data()&v[0] (有一些注意事项)。或者如果你真的真的想要一个数组,你会知道你需要的大小,并可以把你的ints复制到里面。

但是如果行、列和价格构成了一个信息单位(即:如果你要经常把这三个部分放在一起工作,并且永远不需要 "列数的数组"),你需要的是 真的 真正想要的是用一个单一的类型来代表整个单元,并且有一个 std::vector 的。你可以创建一个 struct 类型,或使用 std::tuple<int, int, int>.


0
投票

std::vector 是一个动态大小的容器,正是为了解决你的问题。你可以将值存储在3个容器中

std::vector<int> aRow;
std::vector<int> aCol;
std::vector<int> aPrice;

或者你可以创建一个包含行的值的结构。

struct S {
    int row;
    int col;
    int price;
};

并将所有的值存储在一个容器中

std::vector<S> s;

由于实际问题不明确(标题中你要求提取,正文中你要求容器),我描述一下我提取数据的方法。

打开文件

ifstream inputfile("file.txt");
char c;
int row;
int col;
int price;

并逐行阅读

while (inputfile >> c >> row >> c >> col >> c >> c >> price) {
    s.push_back({row, col, price});
    // aRow.push_back(row);
    // aCol.push_back(col);
    // aPrice.push_back(price);
}

变量 c 是一个帮助变量,用于跳过括号和分号。

© www.soinside.com 2019 - 2024. All rights reserved.