如何从.txt文件读取浮动图形。根据每行开头的名称,我想读取不同数量的坐标。浮标由“空间”分隔。从.txt文件读取浮动图形
例子:triangle 1.2 -2.4 3.0
结果应该是: float x = 1.2/float y = -2.4/float z = 3.0
文件还有更多线条与differens形状可以是更复杂的,但我想如果我知道该怎么做其中的一个我能做到其他人都是我自己的。
到目前为止我的代码:
#include <iostream>
#include <fstream>
using namespace std;
int main(void)
{
ifstream source; // build a read-Stream
source.open("text.txt", ios_base::in); // open data
if (!source) { // if it does not work
cerr << "Can't open Data!\n";
}
else { // if it worked
char c;
source.get(c); // get first character
if(c == 't'){ // if c is 't' read in 3 floats
float x;
float y;
float z;
while(c != ' '){ // go to the next space
source.get(c);
}
//TO DO ?????? // but now I don't know how to read the floats
}
else if(c == 'r'){ // only two floats needed
float x;
float y;
while(c != ' '){ // go to the next space
source.get(c);
}
//TO DO ??????
}
else if(c == 'p'){ // only one float needed
float x;
while(c != ' '){ // go to the next space
source.get(c);
}
//TODO ???????
}
else{
cerr << "Unknown shape!\n";
}
}
return 0;
}
有你试过[sscanf()](http://www.cplusplus.com/reference/clibrary/cstdio/sscanf/)? – jedwards
此外,您的文本文件中的几行可能有助于验证人们提出的任何代码。 – jedwards
@jedwards考虑到它是C++,'sscanf'不会比这个'getc'垃圾好得多。 –