Reading floats from a file in C++

Started by
15 comments, last by the_cyberlord 19 years, 6 months ago
How can you read for example: float values from a file and assign them to a float?
Advertisement
Quote:Original post by the_cyberlord
How can you read for example: float values from a file and assign them to a float?

// It's quite easy in ascii mode.float ReadAsciiFloat(FILE *File) { float Value; fscanf(File, "%f", &Value); return Value;}// And almost as easy in binary mode.// It might get you into portability problems though. Like different byte orders and non IEEE floating point formats.float ReadBinaryFloat(FILE *File) { float Value; fread(&Value, sizeof(Value), 1, File); return Value;}
Using a FILE* handle you can do

float fValue;

fread( &fValue, sizeof( fValue ), 1, handle );

And similar if you're using other functions.

Fruny: Ftagn! Ia! Ia! std::time_put_byname! Mglui naflftagn std::codecvt eY'ha-nthlei!,char,mbstate_t>

Well first of all, have you read the file? Lets presume you have first.

You first need to filter the value to a seperate character-array (this works a bit better, since less can go wrong with the conversion)

If you have filtered the value then you convert it to a float:

float fX = (float)cFilter;


It should work with this, but I make errors too. When you convert something to an other type of variable, then you use the ' type variable-name2 = (type to convert to)variable-name1; ' statement.


In case you want to be more oop [smile], you can use streams. To read from text file:

#include <fstream>using namespace std;...fstream f_in;float   f;f_in.open("file.txt", ios_base::in);f_in >> f;f_in.close();
whoot!
I'm not very advanced you know, can somebody write a piece of code that only reads all the all the values in in a file (ASCII), in the order that they are in the file, seperated by spaces, and converts them to float values and then puts them in a vector?
( and all using the C++ standard libs preferably with <string> and <iostream> )
many thanks!
Since none mentionned these two points :

A) One thing you have to remember when you read atomic types in files is :
endianness (Google)

B) One thing you have to remember about reading structures is :
structure alignment (Google)


If you don't want to have bugs or create complications if someone ports your softare from PC to Mac for intance, remember A).

If you don't want to spend hours figuring out why your favorite importer crashes, just to discover it's because you changed some compiler settings, learn what B) is all about.
"Coding math tricks in asm is more fun than Java"
Simple app that will read all values from file.txt and store them in vector. No error checking is done.

#include <iostream>#include <fstream>#include <vector>using namespace std;int main(void){    ifstream        f_in;    vector<float>   values;    // open file    f_in.open("file.txt", ios_base::in);    // go through whole file    while (!f_in.eof())    {        float       f;        // read value, you don't need to care about spaces, tabs or newlines        f_in >> f;        // add value to vector        values.push_back(f);    }    // close file    f_in.close();    // write values to output    for (vector<float>::iterator it = values.begin(); it != values.end(); ++it)    {        cout << *it << endl;    }    return 0;}


And version without streams:

#include <stdio.h>#include <vector>using namespace std;int main(void){    FILE          *f_in;    vector<float> values;    f_in = fopen("file.txt", "r");    while (!feof(f_in))    {        float   f;        fscanf(f_in, "%f", &f);        values.push_back(f);    }    fclose(f_in);    // write values to output    for (vector<float>::iterator it = values.begin(); it != values.end(); ++it)    {        printf("%f\n", *it);    }    return 0;}
you mean, reading ascii numbers from a file and putting them in a numerical data type automatically converts them?
Quote:Original post by b2b3
Simple app that will read all values from file.txt and store them in vector. No error checking is done.


its actually more simpler than that assuming its just consecutive floats separated by white-space e.g.:

#include <cstdlib>#include <algorithm>#include <iterator>#include <fstream>#include <vector>#include <iostream>int main(int argc, char* argv[]) {   if(argc == 1)      return EXIT_FAILURE;   std::vector<float> vfs;   std::ifstream ifs(argv[1]);   std::copy(std::istream_iterator<float>(ifs),             std::istream_iterator<float>(),             std::back_inserter(vfs));   ifs.close();   std::copy(vfs.begin(), vfs.end(),             std::ostream_iterator<float>(std::cout, ", "));   return EXIT_SUCCESS;}


but with-out the actual file format that just a stab in the dark.

Quote:Original post by the_cyberlord
you mean, reading ascii numbers from a file and putting them in a numerical data type automatically converts them?


doesn't convert, the I/O streams parse text into appropriate type in a type safe manner (when used correctly), they do the parsing for you.

This topic is closed to new replies.

Advertisement