C++ read text file into an array

23,463

Solution 1

Your for loop terminating condition is wrong:

i < monsters->size()

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.

i < 20

Solution 2

monsters->size() is 0 at runtime. Change that line to for (int i=0;i<20;i++).

 string monsters[20];
    ifstream inData;
    inData.open("names.txt");
    for (int i=0;i<20;i++){
        inData >> monsters[i];
        cout << monsters[i] << endl;
    }inData.close();
Share:
23,463
pjmil
Author by

pjmil

pjmil pjmil pjmil

Updated on May 03, 2020

Comments

  • pjmil
    pjmil about 4 years

    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?