要读取的 .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();
}