Saturday, May 22, 2010

C++ Arrays and Input files?

I have an input file and there are three variables in each line. How can I take the variables (say x, y, z) and put y and z into two different arrays?





In other words:


(Input file reads : x y z)





Input %26gt;%26gt; x %26gt;%26gt; y %26gt;%26gt; z





y and z needs to be in two different arrays to find mean of each array .





I know its vague, but I can't think of a better way to explain it. I've tried looking at some Array tutorials, but I get lost. Thanks for any help.

C++ Arrays and Input files?
I'm not sure this helps explain anything to you because you don't make it clear what you aren't understanding. So hopefully this helps somewhat.





int main()


{


int x;


int a[10] = {0};


int b[10] = {0};





ifstream infile("mydata.dat");





int i = 0;





while (infile)


{


infile %26gt;%26gt; x %26gt;%26gt; a[i] %26gt;%26gt; b[i];


//presumably do something with x too


i++;


}





for (int j = 0; j %26lt; i - 1; ++j)


{


cout %26lt;%26lt; a[j] %26lt;%26lt; " " %26lt;%26lt; b[j] %26lt;%26lt; endl;


}


}
Reply:from what i understand.





you want something like


int x[50], y[50], z[50];





for (i = 0; i %26lt; 50; ++i)


ifs %26gt;%26gt; x[i] %26gt;%26gt; y[i] %26gt;%26gt; z[i];





An array in C/C++ is declared as


eg: int arr[50];


The caveat is that array index start from 0 not 1.


So arr[0] is valid in C/C++.


The last value in the array is arr[49] not arr[50]


To reference an element in an array.


Use this form: arr[n] where n is any integer value.


It is recommended that n is not less than 0 and not greater than or equal to the maximum declared. In this case, n should be any value from 0 to 49.


Hope this makes things a little clearer on arrays.


No comments:

Post a Comment