我需要从C++中的文件解析帮助
好吧,所以基本上我有这个文本文件的数字和字母,应该表示多边形的顶点。这部分并不重要,因为我无法从文件解析为int。到目前为止,该函数的样子:我需要从C++中的文件解析帮助
void parseModel(void)
{
int num_vertices, num_faces;
char data[255];
ifstream ifs("rect-skinny.d");
ifs.getline(data, 255);
istrstream ins(data);
ins >> num_vertices;
cout << num_vertices << endl;
ifs.close();
}
我已经尝试了许多不同的方法,所有的给了我不同的,但不正确的答案。由于某种原因,这个输出号码为-858993460。其他时候,当我尝试单独打印数据时,它会输出封闭的括号。我无法弄清楚我做错了什么,因为这似乎应该起作用。输入文件是:
data 8 6
-0.5 1.0 0.3
0.5 1.0 0.3
0.5 -1.0 0.3
-0.5 -1.0 0.3
-0.5 1.0 -0.3
0.5 1.0 -0.3
0.5 -1.0 -0.3
-0.5 -1.0 -0.3
4 1 2 3 4
4 1 5 6 2
4 2 6 7 3
4 5 8 7 6
4 1 4 8 5
4 3 7 8 4
基本上所有我想现在做的就是第一行,并把这些数字分别诠释它变成为num_vertices和NUM_FACES。
阅读文本字符串“data”后,它将包含“data 8 6
”。
该行ins >> num_vertices;
会尝试读取一个整数,但会找到“data 8 6
”,所以会失败。尝试是这样的:
void parseModel(void)
{
int num_vertices, num_faces;
char data[255];
std::ifstream ifs("rect-skinny.d");
ifs.getline(data, 255); // data contains "data 8 6"
std::istrstream ins(data); // ins contains "data 8 6"
ins.ignore(4, ' '); // ins contains " 8 6"
ins >> num_vertices;
std::cout << num_vertices << endl;
ifs.close();
}
+1 - 整数的错误读取导致'badbit'被设置 – 2011-03-23 07:03:48
你可能想要考虑只使用fscanf。
我不明白这会有什么帮助。 fscanf并不比iostream更容易,它不安全,这意味着很容易破坏内存。 – 2011-03-23 07:01:29
对不起,但是-1。这甚至没有试图回答这个问题。 @Michael J:'fscanf'很好 - 特别是当你只用它来解析数字类型的时候。如果您尝试使用它来读取字符串值,您只需要担心它。 – 2011-03-23 07:01:38
@Billy fscanf可能是不安全的。例如 short x; fscanf(myfile,“%d”,&x); 这会损坏内存 – 2011-03-23 07:25:02
这是我会怎么处理这个问题....
如果失败,你可能只想组织你的文件,每一条数据后返回。无论如何,你的生活将会变得更加容易,你的数据将会在数组中。
如果你真的有心使用char数组,你可以将字符串改为char数组。
void parseModel(void)
{
//will read in heading data first, then parse model data
//you could alternatively store your header data in a struct
//or class for better organization
//work with strings, not raw char arrays
string data;
int num_vertices;
int num_faces;
//open the stream
ifstream ifs("rect-skinny.d");
if(!ifs.is_open())
{
cout << "ERROR- ifstream NOT OPEN\n";
}
//read in heading data
ifs >> data;
ifs >> num_vertices;
ifs >> num_faces;
//array of vertex data
float vertices[num_vertices];
//array of faces data
int faces[num_faces];
//loop through all the vertices, reading each into the array
for(int i = 0; i < num_vertices; i++)
{
ifs >> vertices[i];
}
//do the same for the faces
for(int n = 0; n < num_faces; n++)
{
ifs >> faces[n];
}
//closing the stream
ifs.close();
}
您可能想要检查比'is_open'更多的位置,如果它打开但失败这不是真正有用的是吗?:P更重要的是,你通常缺少错误检测。 – 2011-03-23 07:03:20
@比利至少比丢弃前4个字符更好他档案! – anatolyg 2011-03-23 07:18:36
我怀疑这个问题是他的功课。有时候最好不要写出整个解决方案,而是给出一些帮助的线索,然后留下一点让学生去做。 – 2011-03-23 07:29:10
而不是'的std :: istream的::函数getline(字符*,诠释)',为什么不使用'的std ::从'函数getline(的std :: istream的与,的std :: string&)''? (不涉及你的问题,但它是一个更容易地狱) –
2011-03-23 07:04:45