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?
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.
"Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
-Christopher Hitchens
Basics of File I/O here
No No's:
fflush (stdin); gets (); void main ();
Goodies:
Example of fgets (); The FAQ, C/C++ Reference
My Gear:
OS - Windows XP
IDE - MS Visual C++ 2008 Express Edition
ASCII stupid question, get a stupid ANSI
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.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));
Last edited by hk_mp5kpdw; 05-11-2006 at 09:05 AM.
"Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
-Christopher Hitchens
Thank you very much, this works!