Использование ifstream для чтения поплавков

Я пытаюсь прочитать серию чисел с плавающей точкой из файла.out, используя ifstream, но если я выведу их потом, они не будут правильными.

Это мой входной код:

float x, y, z;

ifstream table;
table.open("Resources/bones.out");
if (table.fail())
{
    cout << "Can't open table" << endl;
    return ;
}

table >> x;
table >> y;
table >> z;

cout << x << " " << y << " " << z << endl;

table.close();

Мой входной файл:

0.488454 0.510216 0.466979
0.487242 0.421347 0.472977
0.486773 0.371251 0.473103
...

Теперь для тестирования, я просто читаю первую строку в xy а также z и мой вывод

1 0 2

Есть идеи, почему я не получаю правильный вывод?

2 ответа

#include <fstream>
#include <strtk.hpp>   // http://www.partow.net/programming/strtk

std::string filename("Resources/bones.out");

// assuming the file is text
std::fstream fs;
fs.open(filename.c_str(), std::ios::in);

if(fs.fail())  return false;   

const char *whitespace    = " \t\r\n\f";

std::string line;
std::vector<float> floats;
std::vector<std::string> strings;
float x = 0.0, y = 0.0, z = 0.0;
std::string xs, ys, zs;

// process each line in turn
while( std::getline(fs, line ) )
{
    // Removing beginning and ending whitespace
    // can prevent parsing problems from different line endings.
    // formerly accomplished with boost::algorithm::trim(line)

    strtk::remove_leading_trailing(whitespace, line);


    // strtk::parse combines multiple delimiters in these cases

    if( strtk::parse(line, whitespace, floats ) ) 
    {
         std::cout << "succeed" << std::endl;
         // floats contains all the values on the in as floats
    }

    if( strtk::parse(line, whitespace, strings) ) 
    {
         std::cout << "succeed" << std::endl;
         // strings contains all the values on the in line as strings
    }

    if( strtk::parse(line, whitespace, x, y, z) ) 
    {
         std::cout << "succeed" << std::endl;
         // x,y,z contain the float values.  parse fails if more than 3 floats are on the line
    }

    if( strtk::parse(line, whitespace, xs, ys, zs) ) 
    {
         std::cout << "succeed" << std::endl;
         // xs,ys,zs contain the strings.  parse fails if more than 3 strings are on the line
    }
}

Вот как бы я это решил. Вы можете выбрать способ анализа данных.

Я работал с этим раньше и кое-что, что я хотел бы сделать, это как код ниже, где вы читаете текстовый файл построчно и используете getline и строку, чтобы поместить текст в переменные. Вам не нужно использовать массив, так как он ограничен элементами, но используйте вектор и таким образом вы можете добавлять его динамически.

    string xs;
    string ys;
    string zs;
    ifstream infile;
    someArray[50];
    infile.open("some file.txt");

    if (!infile)
    {
        cout << "no good file failed! \n" << endl;
    }

    while (infile.good())
    {
        for (int i = 0; i < 49; ++i)
        {
            getline(infile, xs);
            //Saves the line in xs.
                infile >> p[i].xs;

            getline(infile, ys, ',');
            infile >> p[i].ys;
            getline(infile, zs, ',');
            infile >> p[i].zs;

        }
        //infile >> p.fromFloor; */



    }

    infile.close(); 
}
Другие вопросы по тегам