Чтение плавающих файлов из .txt файла
Как я могу читать поплавки из TXT файла. В зависимости от имени в начале каждой строки я хочу прочитать другое количество координат. Поплавки разделяются пробелом.
Пример: triangle 1.2 -2.4 3.0
Результат должен быть:
float x = 1.2 / float y = -2.4 / float z = 3.0
В файле больше строк с различными формами, которые могут быть более сложными, но я думаю, что если я знаю, как сделать один из них, я могу сделать остальные самостоятельно.
Мой код:
#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;
}
Ответы
Ответ 1
Почему бы просто не использовать потоки С++ обычным способом, а не всем этим безумием getc
:
#include <sstream>
#include <string>
for(std::string line; std::getline(source, line); ) //read stream line by line
{
std::istringstream in(line); //make a stream for the line itself
std::string type;
in >> type; //and read the first whitespace-separated token
if(type == "triangle") //and check its value
{
float x, y, z;
in >> x >> y >> z; //now read the whitespace-separated floats
}
else if(...)
...
else
...
}
Ответ 2
Это должно работать:
string shapeName;
source >> shapeName;
if (shapeName[0] == 't') {
float a,b,c;
source >> a;
source >> b;
source >> c;
}