Hey, I'm having a litte bit of an issue when counting the amount of array entries when using ifstream to input values in to two double arrays.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cmath>
#include <iomanip>
using namespace std;
const int arraymax = 1000;
// prototype function declaration(s)
int main(){
char infilename[50];
char outfilename[50];
// read the input and output filenames
cout << "Please enter the input filename: " << endl;
cin >> infilename;
cout << "Please enter the output filename: " << endl;
cin >> outfilename;
// declare arrays, open input file and read numbers into arrays
double xarray[arraymax];
double yarray[arraymax];
int n = 0;
ifstream input(infilename);
if(!input){
cerr << "Failed to open input file " << infilename << endl;
exit(1);
} // error message appears if the input file fails to open, it then quits execution.
for(int i = 0; input && i < arraymax; ++i, n++){
input >> *(xarray + i);
input >> *(yarray + i);
}
}
| |
The variable
int n
is what I use to count the array size. Everytime the for loop inputs values in to my arrays, it adds one to
n
and then carries out the for loop until input no longer holds true or the local variable
i
reaches the maximum allowed size of my array (1000).
The problem I'm having, is that my arraysize
n
seems to overcount by one. This forces me to set
int n = -1
, but this causes problems when I have an input file which contains 1000 values (the maximum size of my array) that have to be placed in to each array.
However, I notice that;
1 2 3 4 5 6 7 8 9 10 11 12
|
int n = 0
int j = 0;
while(input){ // in is true until "end-of-file"
if(j >= arraymax) break;
// word[i] is a string. Input into a string reads up to
// the next space, or newline
if(input >> *(xarray+j) >> *(yarray+j)){
j++;
n++;
}
}
| |
Solves all my problems.
So I'm trying to deduce the difference here, and hoping you could help me. My input file looks like this;
2 1.69
3 3.25
4 2.44
5 3.45
6 6.29
7 3.94
8 5.23
9 5.78
10 6.31
11 8.25
12 7.84
What I can gather, is that in my first for loop. Input will STILL test true once it has reached the last part of my input file (past 7.84). However, once it tries to read in to the double arrays after having reached the last part, it will then test false - this means that
int n
will over count by one.
In the second while loop, it tests whether input is still valid. If it does, the if statement checks if anything has actually been added in to the arrays, if anything has then it adds one to
int n
. So, even though input still tests true once it reaches the last part of my input file, it will only add one to
int n
if anything is actually input in to the arrays.
Is this correct? (I'm still very new to this).