Reading a file and loading it into an array?

This is a discussion on Reading a file and loading it into an array? within the C++ Programming forums, part of the General Programming Boards category; Say I make a database of Team names in a text file, each one is on a new line. How ...

  1. #1
    Registered User Dual-Catfish's Avatar
    Join Date
    Sep 2001
    Posts
    802

    Reading a file and loading it into an array?

    Say I make a database of Team names in a text file, each one is on a new line. How would I read this file, and load each into an element of an array of type string?

    I know how to open files, but I just don't know how to seek to the next line. I read the tutorial on this page but it just covers input of 1 string..

    Any help would be appreciated.

  2. #2
    Unregistered
    Guest
    if names are without spaces use the >> operator. Otherwise use getline().

    char names[150][30] = {"\0"}; //array of 150 empty strings
    ifstream fin("myFile.txt");//if myFile.txt is in same folder as compiler
    int i = 0;

    //you now myFile.txt is not empty but it could have up to 150 names

    fin.getline(names[i++], 29);

    while(!fin.eof() && i < 150)
    {
    fin.getline(names[i++], 29)
    }

  3. #3
    Registered User Dual-Catfish's Avatar
    Join Date
    Sep 2001
    Posts
    802
    Thank you so much
    I pieced together a demo, using what you said, although I can't seem to catch when the last element was reached..
    for example

    if (names[i] != " " || names[i] != "\0")
    {
    cout << names[i];
    cout << "\t";
    }

    doesn't work.

    Although it still prints up to 150, with all the spaces and such, pushing everything that was printed off the screen.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Loading a file of words into dynamic char**
    By strakerc in forum C Programming
    Replies: 11
    Last Post: 07-11-2008, 07:20 PM
  2. Error when loading 3ds file
    By The Wazaa in forum C++ Programming
    Replies: 6
    Last Post: 01-24-2006, 07:27 AM
  3. multiple file loading. so fruturated! help!
    By psychopath in forum Game Programming
    Replies: 5
    Last Post: 05-09-2005, 05:13 PM
  4. loading binary file into an int array!!
    By strike in forum C Programming
    Replies: 2
    Last Post: 03-20-2005, 08:50 AM
  5. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21