如何将逗号分隔的文本文件读入数组

How to read a comma delimited text file into arrays

本文关键字:文件 文本 数组 分隔      更新时间:2023-10-16

我一直在做这个项目,并且一直在读取文本文件,中间只有空格而不是逗号,所以我需要更新我在文件中读取数组的方式。我尝试过使用stringstream()和getline(),但没有运气。有谁知道我如何将此文件读入数组?

这就是我以前的做法

void readData(ifstream& inputFile, double lat[], double lon[], double yaw[], int& numLines)
{
// Read in headers.
string header;
getline(inputFile, header);
// Read in data and store in arrays.
for (int i = 0; i < numLines; i++)
{
    if (inputFile >> lat[i])
    {
        inputFile >> lon[i];
        inputFile >> yaw[i];
    }
}

但我不确定如何修改它以将此类文件读取到数组中,而且我唯一感兴趣的是

纬度

经度

海拔高度(英尺)

速度(英里/小时)

全球定位系统

权力

偏航

电机开启

834,,,,,,,,,,,,,,,,
latitude,longitude,altitude(feet),ascent(feet),speed(mph),distance(feet),max_altitude(feet),max_ascent(feet),max_speed(mph),max_distance(feet),time(millisecond),gps,power,pitch,roll,yaw,motor on
43.5803481,-116.7406331,0,0,0,0,0,0,0,0,539,10,97,178,180,141,0
43.5803481,-116.7406329,0,0,0,0,0,0,0,0,841,10,97,178,180,141,0
43.5803482,-116.7406328,0,0,0,0,0,0,0,0,1125,10,97,178,180,141,0
43.5803481,-116.7406329,-1,0,0,0,0,0,0,0,1420,10,97,178,180,141,0
43.580348,-116.7406328,0,0,0,0,0,0,0,0,1720,10,97,178,180,140,0
43.5803479,-116.7406326,-1,0,0,0,0,0,0,0,2023,10,97,178,180,140,0
43.5803478,-116.7406326,0,0,0,0,0,0,0,0,2344,10,97,178,180,140,0
43.5803476,-116.7406329,-1,0,0,0,0,0,0,0,2620,10,97,178,180,140,0
43.5803475,-116.7406329,-1,0,0,0,0,0,0,0,2922,10,97,178,180,140,0
43.5803473,-116.7406329,0,0,0,0,0,0,0,0,3221,10,97,178,180,140,0

如果有人能指出正确的方向,那就太好了。谢谢

您需要将这些逗号提取为 char 类型的变量:

std::ifstream f("d:\temp\z.txt");
string s;
double lat, lon, alt, asc, speed, dist, max;
vector<double> lat_vec, lon_vec, asc_vec, speed_vec, dist_vec, max_vec;
char c;
while (!f.eof()) {
    f>>s; // get one line
    stringstream st(s);
    // below, eat first number, then comma, then second number, etc.
    if (st>>lat>>c>>lon>>c>>alt>>c>>asc>>c>>speed>>c>>dist>>c>>max) {
        lat_vec.push_back(lat); lon_vec.push_back(lon);
        asc_vec.push_back(asc); speed_vec.push_back(speed);
        dist_vec.push_back(dist); max_vec.push_back(max);
    }
}
// if you really need arrays, not vectors
double *dist_ar = new double[dist_vec.size];
for (int i=0;i<dist_vec.size(); i++)
    dist_ar[i]=dist_vec[i];
return 0;