c++ 提取txt格式的文件中的内容到vector

  1. 背景
    提取同目录下的 xyz.txt 文件第一列数字到x_vector,第二列数字到y_vector,第三列数字到z_vector,并查看是否正确提取。

xyz.txt 的内容:

1.0 2.0 2.5
1.2 3.4 5.8
3.4 6.2 7.8
4.3 2.6 9.5
  1. 代码
    Extract_FileContents2vector.cpp
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>

void extract_xyz(std::vector<float>& v_x, std::vector<float>& v_y,std::vector<float>& v_z);
void print_v(std::vector<float>& v_);

int main(){

    std::vector<float> x, y, z;
    extract_xyz(x, y, z);
    std::cout << "x vector: " << std::endl;
    print_v(x);
    std::cout << "y vector: " << std::endl;
    print_v(y);
    std::cout << "z vector: " << std::endl;
    print_v(z);
    
    return 0;
}

void extract_xyz(std::vector<float>& v_x, std::vector<float>& v_y,std::vector<float>& v_z){
    std::ifstream file("../xyz.txt");
    std::string line, word;
    if(!file)
    {
        std::cout << "Cannot open xyz.txt" << std::endl;
        exit(1);
    }

    while (std::getline(file, line))
    {
        std::cout << line << std::endl;
        std::istringstream words(line);//字符串str必须是使用空格分开的。为了得到各个字串,可以进行按照空格的坐标进行分割,但是可以借助流进行自动分割
        if(line.length() == 0){
            continue;
        }
        for (int i = 0; i < 3; i++)    //有3列
        {
            if(words >> word){
                if(i == 0){
                    v_x.push_back(std::stod(word));   //第一列是x
                }
                if(i == 1){
                    v_y.push_back(std::stod(word));   //第二列是y
                }
                if(i == 2){
                    v_z.push_back(std::stod(word));   //第二列是z
                }
            }
            else{
                std::cout << "Error for reading xyz.txt" << std::endl;
                exit(1);
            }
        }
    }
    file.close();
};

void print_v(std::vector<float>& v_){

    for(int i = 0; i< v_.size();i++){
        std::cout << v_[i] << std::endl;
    }
}

CMakeLists.txt

cmake_minimum_required(VERSION 3.10)
project(test)

set(CMAKE_CXX_STANDARD 14)
set(CMAKE_BUILD_TYPE "Release")

add_executable(Extract_FileContents2vector Extract_FileContents2vector.cpp)
  1. 打印内容
1.0 2.0 2.5
1.2 3.4 5.8
3.4 6.2 7.8
4.3 2.6 9.5
x vector: 
1
1.2
3.4
4.3
y vector: 
2
3.4
6.2
2.6
z vector: 
2.5
5.8
7.8
9.5
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值