I have a text file filled with decimals and I am trying to pass that data from the text file into an array. I have succeeded with reading in the data from the text file but the issue I have is the last value is read in as '0'. Why is this?
the file is good until you read the end of file marker.
so you start the loop, its good, you read, nothing there (eof marker hit), then you do what?
The loop begins, reads the data from the file then hits the end of file marker. I have other functions to do some calculations using the data from the text file. Thank you for the assistance, it seems that I over complicated what seemed to be a simple solution. The only issue I have remaining is that the loop prints a '0' after all the data has been read into the array.
1 2 3 4 5 6 7 8 9 10 11 12
void read(std::ifstream& object, double v[])
{
std::string data;
int i = 0;
while (object.good())
{
object >> v[i];
std::cout << v[i] << std::endl;
++i;
}
object.close();
}
#include <iostream>
#include <fstream>
// accept all streams, not just ifstream
size_t read( std::istream& object, double v[], size_t N );
int main()
{
// no global values required
constexpr size_t MAX {20};
double V[MAX];
std::ifstream ifile("voltage.txt");
size_t count = read( ifile, V, MAX );
// show
for ( size_t e=0; e < count; ++e ) std::cout << V[e] << '\n';
}
// reads at most N double values from object and stores them in v
// returns count of stored values
size_t read( std::istream& object, double v[], size_t N )
{
size_t i {0};
double input {};
while ( i < N && object >> input )
{
v[i] = input; // write only valid values into the array
++i;
}
return i;
}