- 背景
提取同目录下的 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
- 代码
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.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