我有一个文本文件安排为:
Diam
<D> 4.2
05:21:26 02:Apr:2012
Point 1
<X> 2
<Y> 5
<Z> 6
Point 2
<X> 4
<Y> 2
<Z> 0
Point 3
<X> 4
<Y> 1
<Z> 2
End
End
我需要做两件事,首先我需要读取点数,所以基本上读取了以 Point 开头的行数,为此我写了:
#include <iostream>
#include <string>
using namespace std;
int main()
{
//count number of data points in file (only count lines starting with P)
const char FileName[] = "myfile.txt";
int num = 0.;
string line;
ifstream file;
file.open (FileName);
while(file.eof() == false)
{
getline(file, line);
if (line[0]=='P') num++;
}
file.close();
return 0;
}
这给了我正确的点数(尽管欢迎对代码进行改进),其次我需要阅读 x、y 和 z 坐标并忽略其他所有内容。不知道该怎么做,有什么建议吗?
提前致谢!
编辑:
感谢大家的好主意和答案!Obvlious 船长提供了一个很好的答案,我想看看它是否可以调整一下。
因此,事实证明 .txt 文件将具有以下格式:
Diam
<D> 4.2 5 6 4 2
05:21:26 02:Apr:2012
Point 1
<X> 2 5 6 4 2
<Y> 5 4 4 8 3
<Z> 6 7 6 0 2
Point 2
<X> 4 2 6 4 2
<Y> 2 3 5 8 4
<Z> 0 7 6 3 2
Point 3
<X> 4 0 6 2 2
<Y> 1 5 6 7 4
<Z> 2 0 6 5 3
End
End
同样,我只需要第一列值,之后的所有其他内容都可以丢弃。我int
为简单起见,但数字将是double
. 阅读后,我试图将值放在犰狳矩阵中,所以我的矩阵看起来像:
cout << matrix << endl;
2 5 6
4 2 0
4 1 2
因此,我修改了 Captain Obvlious 的解决方案,将数据放入矩阵中:
#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
#include <sstream>
#include <stdexcept>
#include <armadillo>
using namespace std;
using namespace arma;
int main()
{
mat matrix(3,3); //here is where I set the size of the matrix,
//different files have different number of points,
//that's why I use my counting points code to set the size.
const char FileName[] = "myfile.txt";
string line;
ifstream file;
file.open (FileName);
for(;;)
{
getline(file, line);
if( file.eof() ) {
break;
}
if (line.size() && line[0]=='P')
{
// Change "int" to "double" if necessary.
struct { double x, y, z; } data;
for(int i = 0; i < 3; i++)
{
getline(file, line);
if(line.size() > 3 && line[0] == '<' && line[2] == '>')
{
string::value_type pointElement = line[1];
// skip spaces and process data here to get the value
string::size_type offset = line.find(' ');
if(string::npos == offset)
{
throw invalid_argument("Invalid data format");
}
stringstream sline(line.substr(offset));
int value;
if(!(sline >> value))
{
throw invalid_argument("invalid data format");
}
switch(pointElement)
{
case 'X': data.x = value; break;
case 'Y': data.y = value; break;
case 'Z': data.z = value; break;
default:
// error in data format
throw invalid_argument("invalid data format");
}
}
else
{
// error in data format
throw invalid_argument("invalid data format");
}
}
// Do something with the values in data
cout
<< "point[x=" << data.x
<< ", y=" << data.y
<< ", z=" << data.z
<< "]" << endl;
// place data in matrix
// need to loop over k where k is the row of the matrix
matrix(k,0) = data.x; // format is matrix(rows,columns)
matrix(k,1) = data.y;
matrix(k,2) = data.z;
}
}
file.close();
return 0;
}
不确定将循环放置在 k 上的位置,该循环设置矩阵的行以分配值。很抱歉这篇超长的帖子,并提前感谢您的帮助。在我看来,这是非常有用的东西,可供将来参考。