읽을 .txt 파일은 다음 data.txt와 같습니다.
-83.635047 -248.884343 -15.649366
-83.237317 -248.651216 -15.458514
-82.838610 -248.419124 -15.266673
-82.438903 -248.188020 -15.075844
-82.039185 -247.956894 -14.886015
-81.638502 -247.727802 -14.695220
-81.236808 -247.499677 -14.506436
-80.835137 -247.272574 -14.316676
-80.432466 -247.046460 -14.127926
-80.028807 -246.821357 -13.939188
-79.624149 -246.597244 -13.751461
-79.219502 -246.374130 -13.563757
-78.813867 -246.153006 -13.377087
-78.407233 -245.931893 -13.190406
-77.999622 -245.712792 -13.003759
-77.592011 -245.494667 -12.818134
-77.182412 -245.277567 -12.632510
위의 데이터 텍스트는 다음과 같은 특징을 가지고 있는데, 각 줄의 데이터 개수는 동일하고 공백을 사용하여 데이터를 구분하며, 데이터 파일을 읽는 방법에는 단어 단위와 줄 단위가 있습니다.
#include <iostream>
#include <sstream>
#include <fstream>
using namespace std;
int main()
{
// 逐词读取,按照空格进行分隔
ifstream fin("data.txt");
string s;
while(fin>>s)
{
cout<<s<<endl;
}
fin.close();
s.clear();
// 逐行读取,按照每行结束的回车区分
fin.open("data.txt");
while(getline(fin,s))
{
cout<<s<<endl;
}
fin.close();
s.clear();
return 0;
}
// 逐词读取,按照空格进行分隔
ifstream fin("bottom.txt");
string s;
while (fin >> s)
{
cout << s << endl;
}
fin.close();
s.clear();
// 逐行读取,按照每行结束的回车区分
fin.open("bottom.txt");
while (getline(fin, s))
{
cout << s << endl;
}
fin.close();
s.clear();
작업 데이터를 한 줄씩 읽는 것은 융통성이 없고 한 단어씩 읽는 데이터는 너무 크기 때문에 한 줄씩 먼저 생각한 다음 한 단어씩 읽어서 각 줄에서 흥미로운 데이터를 추출하는 것이 자연스럽습니다.
ifstream fin;
istringstream iss;
string s;
double t;
vector<double> tube;
int count = 0;
// 逐行读取,将每一行数据读取到字符串 s 中
fin.open("bottom.txt");
while (getline(fin, s))
{
iss.clear();
iss.str(s);
// 逐词读取,遍历每一行中的每个词 t
while (iss >> t)
{
cout << t << " ";
}
cout << endl;
}
위의 방법에 따라 관심 있는 데이터를 추출할 수 있는데, 예를 들어 data.txt 파일의 첫 번째, 두 번째 및 세 번째 열 데이터를 추출하여 bottom.csv 파일에 저장합니다(Matlab이 곡선을 그리기에 편리함) ):
ifstream fin;
ofstream outFile; // 2、创建流对象
istringstream iss;
string s;
double t;
vector<double> tube_x;
vector<double> tube_y;
vector<double> tube_z;
int count = 0;
// 按行读取,将每一行数据读取到字符串 s 中
fin.open("bottom.txt");
while (getline(fin, s))
{
iss.clear();
iss.str(s);
// 逐词读取,操作/提取 你感兴趣的数据
while (!iss.eof())
{
iss >> t;
count += 1;
if (count % 3 == 1)
{
tube_x.push_back(t);
}
if (count % 3 == 2)
{
tube_y.push_back(t);
}
if (count % 3 == 0)
{
tube_z.push_back(t);
}
}
count = 0;
}
int num = tube_x.size();
cout << "num=" << num << endl;
for (int j = 0; j < num; j++)
{
cout << "tube_x:" << tube_x[j] << " " << "tube_y:" << tube_y[j] << " " << "tube_z:" << tube_z[j] << endl;
outFile.open("bottom.csv", ios::app);
outFile << tube_x[j] << "," << tube_y[j] << "," << tube_z[j] << "\n";
outFile.close();
}