Re: Reading an array from file?
fdm wrote:
[..]
I have now tried:
std::ifstream infile(path_to_file.c_str(), std::ios_base::in);
// if your file does have the leading bracket: Yes it does
std::vector<double> values;
while (infile) {
char dummy_char;
if (infile >> dummy_char) {
double d;
if (infile >> d) {
values.push_back(d);
std::cout << "val = " << d << std::endl;
}
}
}
The loop only gets executed once since all the values are on one line
(this is the format) and no doubles are created.
Should the line not be read and then parsed to doubles where ',' is used
as a delimiter?
OK, here are the results:
------------------------- code
#include <iostream>
#include <fstream>
#include <vector>
int main()
{
std::string path_to_file("testdoubles.txt");
std::ifstream infile(path_to_file.c_str(), std::ios_base::in);
// if your file does have the leading bracket: Yes it does
std::vector<double> values;
while (infile) {
char dummy_char;
if (infile >> dummy_char) {
double d;
if (infile >> d) {
values.push_back(d);
std::cout << "val = " << d << std::endl;
}
}
}
std::cout << "read " << values.size() << " doubles\n";
return 0;
}
-------------------------------- file 'testdoubles.txt'
[-0.00231844, -0.02326, 0.0484723, 0.0782189, 0.0917853]
-----------------------------------------------------------
Compiled with VC++ 2008 and run, here is the output:
-------------------------------------
val = -0.00231844
val = -0.02326
val = 0.0484723
val = 0.0782189
val = 0.0917853
read 5 doubles
-------------------------------------
I took your first 5 doubles, closed them with the bracket, and placed
the TXT file next to the executable. Everything went fine, as you can
see here. Would you take my word for it? <shrug> Now, I have no idea
what you're doing wrong, but you must be doing something wrong.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask