C++生成等高线1

读取文件

文件的格式如下
txt文件

这个文件通过“,”对数据进行隔开,抛开第二列数据,其余数据分别是点名,X坐标,Y坐标,H坐标,因此读取文件的重点在于分割,这里使用的是find()函数和strstr()函数组合进行分割操作,最终保存在列表points中

find()函数

find()函数是用来进行字符串中特定字段查找的函数,其中,第一个参数是查找的字符或者字符串,第二个参数是用来确定开始查找的位置,返回的是查到找的字符位置。
index2 = line.find(',', index1 + 1);这里是指在字符串line中查找 ‘,’,从index+1位置开始,找到该字符后返回其位置赋值给index2

substr()函数

substr()函数是用来按照指定位置和长度截取字符串,第一个参数是开始位置,第二个位置是截取长度,返回截取的字符串。
p.name = line.substr(index1, index2 - index1);这里是将line字符串,从第index1位置,截取index2 - index1个字符,最终赋值给p.name

读取如下

利用库文件fstream进行读取,使用ifstream创建读取文件流,用**getline()**函数读取每一行数据,利用上面提到的两个函数进行截取操作,最终赋值给相关变量。

最后的函数代码

void openFile(string path, list<GroundPoint> &points) {   //读取文件的函数
    ifstream  ifs(path);
    if (!ifs.is_open())
        cout << "Open Error!" << endl;
    string lines[5];
    string line;
    int index1 = 0;
    int index2;
    while (getline(ifs, line)) {
        index1 = 0;
        index2 = line.find(',', index1 + 1);
        p.name = line.substr(index1, index2 - index1);
        index1 = index2;
        index2 = line.find(',', index1 + 1);
        index1 = index2;
        index2 = line.find(',', index1 + 1);
        p.x = stod(line.substr(index1 + 1, index2 - index1 - 1));
        index1 = index2;
        index2 = line.find(',', index1 + 1);
        p.y = stod(line.substr(index1 + 1, index2 - index1 -1));
        index1 = index2;
        index2 = line.find(',', index1 + 1);
        p.h = stod(line.substr(index1 + 1, index2 - index1 - 1));
        points.push_back(p);
        lineNum++;
    }
}

由于写的匆忙,代码有很明显的冗余,但是能完成最简单的读取操作。

  • 14
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值