I’m trying to read a text file containing 20 names into an array of strings, and then print each string to the screen.
string monsters[20];
ifstream inData;
inData.open("names.txt");
for (int i=0;i<monsters->size();i++){
inData >> monsters[i];
cout << monsters[i] << endl;
}inData.close();
However when I run this code the loop is executed but nothing is read into the array. Where have I gone wrong?
Your for loop terminating condition is wrong:
This will actually call size() on the first string in your array, since that is located at the first index. (monsters is equivalent to monsters[0]) Since it’s empty by default, it returns 0, and the loop will never even run.
Remember, C++ does not have a size() operator for arrays. You should instead use the constant 20 for your terminating condition.