Hello, so im trying to read an unknown number of numbers into an array, then do some math to those numbers. Im stuck on reading the data into an array...I cant quite figure out how to input the data into an array. can someone point me in the right direction? I've only included the part of the program that i'm having trouble with, if you need, i can post the entire thing
The first thing that I see is that you have more {s than }s. Edit: nevermind, I see that you have no { in that if statment on line 15. The indenting is a little strange and needs to be corrected..
I see that you have InStream.close(); inside of your reading while loop on line 17. That means that your file will close after your first read. You don't want that.
Regarding HiteshVaghani1's suggestion: I don't think int array[' '] is the way to go. If you want to zero everything, do this: int arr[counter] = {0};
Note that I've replaced "array" with "arr" as array is a type in C++11 and so your code will not be compilable in the near future. However, this is still not the correct solution because you can't create an array with a non-constant value. You'd have to use dynamic memory allocation.
THerefore what you want is this for line 20: int* arr = newint[counter];
To rewrite your function in a more simple way, try somethign like this (you have to #include <vector>).
Remember, in programming, you shouldn't really ever have to do something twice. Here you are opening the file to check its length, closing it, then opening it again to read. Just read it once and "push_back" as you go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
void functions::ReadData(int argc, char *argv[])
{
char placeholder;
std::vector<char> arr;
std::ifstream InStream(argv[1]);
while (true)
{
InStream >> placeholder;
if (InStream.good())
arr.push_back(placeholder);
elsebreak;
}
InStream.close();
for(int i = 0; i < arr.size(); i++)
std::cout << arr[i] << std::endl;
}
but i keep getting an extra element at the end of the array, and its always 0. ( so if my text file has the numbers 1 2 3 4, my array becomes 1 2 3 4 0.) can you see why this is?