Basically, I'm not sure why this is happening, but I really want to get it figured out. This is an idea I had and I'm trying to get it to work.
So what I am trying to do: Read strings from a file and store them into an array, basically.
But, I wanted to do this:
instead of initializing the size of the array for some given constant number, I wanted to have a loop which first read the number of lines in the file and assign that value into a variable. Therefore, that value will be the size of the array since that value will correspond to the amount of elements I want to store in the array. I want for each line of text in the file, so for each string, to be one element of the array.
Here is the code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
ifstream the_file;
int i, j, z;
string lineCount;
the_file.open("sentence.txt");
j = 0;
while(!the_file.eof())
{
getline(the_file, lineCount);
j++;
}
z = j;
string array[z];
for (i = 0; i < z; i++) {
getline(the_file, array[i]); // Array is empty
cout << i << " " << array[i] << endl;
}
cout << z << endl;
return 0;
}
So then after getting this number, I next want to actually store the elements in the array. For this part, I went with a for loop to attempt that and had the loop execute (array size - 1) number of times to correspond to each element being stored within one index of the array.
I just don't understand why, after running it, it shows that the array is empty. It shows that the array is the size corresponding to the number of lines in the file, yet there aren't any elements, it looks like, in any of the memory spaces.
The thing is, I tried simply setting the array to a given constant size. So basically just simply read elements from a file and store them in the array without doing that first loop to determine what size to set the array. In this case, it works fine and all of the elements get stored normally and none of the memory spaces are empty.
But why is it that if I wanted to do a loop in order to get the value to correspond to the size I want the array to be, and then attempt to store those elements, it's like the file doesn't get read correctly anymore and the assigned memory spaces are empty?
Here is the output:
/Users/macuser/CLionProjects/PA2supp/cmake-build-debug/PA2supp
0
1
2
3
4
5
Process finished with exit code 0
Here is the file that I want read, this is "sentence.txt". Like I said, I want each line to be an element in my array
This is just one sentence.
This is the second sentence.
This is the third sentence.
This is the fourth sentence.
Fifth sentence right here.
Please don't suggest to use a vector, while I am aware of some of the benefits with vectors, I actually really want to do this specific thing using an array.