How to read from a text file?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • kino
    New Member
    • Feb 2011
    • 19

    How to read from a text file?

    Hello,

    I am supposed to read from a text file a series of numbers and then store them in a struct array.

    Here's my code:

    Code:
    int main()
    {
        ifstream In;
        string folder, filename, name2, line;
        int i = 0;
        
        cout << endl << "Enter the name of the folder" << endl;
         cout << "Follow the format: c:/your_folder_name/ :";
         cin >> folder;
         cout << "Enter the name of the file: " ;
         cin >> filename;
        
         name2 = folder + filename + ".txt";
         In.open(name2.c_str());
         
         
       do
       { 
            
             In >> array[i].var1 >> array[i].var2 >> array[i].var3;
             i++;
             cout << i << " " << array[i].id;
            
       } while (getline(In, line));
       
    
       In.close();
       system ("PAUSE");   
       return 0;
    }
    And this is the input file:

    1 1230 1420
    2 1150 1115
    3 1520 1314
    4 1345 1234
    5 1130 1230
    6 1120 0430
    7 1720 1810
    8 1122 1125
    9 1123 1130
    10 1125 1132
    23 1145 1122


    The code is not reading the file at all. Also the variable 'i' being used is not incrementing either. Could anyone please help?
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    What output do you get?
    How is array declared?

    You output array[i].id and that member is never assigned to.

    Comment

    • kino
      New Member
      • Feb 2011
      • 19

      #3
      Sorry, I should have mentioned it earlier, I declared it as a global array. Thanks for replying, my code is working now, I used vectors to declare an array and get the file data instead of the method above.

      Comment

      Working...