For example, this is a content of some txt file:
0.2 0.3 0.1 1.6
I'd like to load these numbers in some array and use them in a program. How do I do that?
Printable View
For example, this is a content of some txt file:
0.2 0.3 0.1 1.6
I'd like to load these numbers in some array and use them in a program. How do I do that?
Use a loop. Unless you know there will always be a fixed number of values in the file to read into the array, you'd be better off reading into a vector instead (or some other STL container) since it will grow to accommodate any number of values.
Basics of File I/O here
Of course, vector is better, I said array for simplicity. I can't use a loop, becoase I don't know the basis of reading from files. I'm not asking for algoritam (although I would not mind :) ), just commands that can help read list of numbers from a txt file.Quote:
Originally Posted by hk_mp5kpdw
Richie T gave the link, but I really can't understand how to solve my problem just by knowing how to open a file. I'd like to know how to read from some position in file, and then when program reads the data, that it can convert it to double, becoase I need it to read numbers not string. If anyone can help, I would appreciate it.
It's really simple, basically you want to do something similar to this:
edit: If you don't want a loop in your code, you can use the copy function in the <algorithm> header to replace the while loop and push_back lines in the example above as follows:Code:#include <fstream>
#include <vector>
using namespace std;
...
ifstream in("NameOfFile.txt"); // ifstream objects are for reading
vector<double> dbl_vect; // vector container to hold values read from file
double temp; // Temporary variable
while( in >> temp ) // While there is stuff to read from file...
dbl_vect.push_back(temp); // ... push double read from file onto vector
You also wouldn't need the temp variable.Code:#include <algorithm>
#include <iterator>
...
copy(istream_iterator<double>(in),istream_iterator<double>(),back_inserter(dbl_vect));
Thank you very much, this works! :)