Results 1 to 6 of 6

Thread: Open File

  1. #1

    Thread Starter
    Stuck in the 80s The Hobo's Avatar
    Join Date
    Jul 2001
    Location
    Michigan
    Posts
    7,256

    Open File

    How can I write a function to open a file (say "C:\list.txt") and add each item in the file to an array using a newline as a deliminator?
    My evil laugh has a squeak in it.

    kristopherwilson.com

  2. #2
    Frenzied Member
    Join Date
    Jul 1999
    Posts
    1,800
    Code:
    #include <iostream.h>
    #include <fstream.h>
    
    int main()
    {
         ifstream InFile("list.txt", ios::nocreate);
         
         char mylist[100][100];
         for(int i=0; i<=99; i++)
         {
              InFile>>mylist[i];
         }
         return 0;
    }
    I think that will work.

  3. #3

    Thread Starter
    Stuck in the 80s The Hobo's Avatar
    Join Date
    Jul 2001
    Location
    Michigan
    Posts
    7,256
    Thanks. It gave me a good start.
    My evil laugh has a squeak in it.

    kristopherwilson.com

  4. #4
    Monday Morning Lunatic parksie's Avatar
    Join Date
    Mar 2000
    Location
    Mashin' on the motorway
    Posts
    8,169
    The standard way

    Code:
    #include <iostream>
    #include <string>
    #include <vector>
    
    using namespace std;
    
    int main() {
        ifstream input("list.txt");
    
        if(!input)
            return -1;
    
        vector<string> lines;
        string temp;
    
        while(!input.eof()) {
            getline(input, temp);
            lines.push_back(temp);
        }
    
        cout << "There are " << lines.size() << " lines." << endl;
    }
    I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
    -- Linus Torvalds

  5. #5
    Frenzied Member
    Join Date
    Jul 1999
    Posts
    1,800
    I was actually thinking you'd fix that when I was typing fstream.h

  6. #6
    Monday Morning Lunatic parksie's Avatar
    Join Date
    Mar 2000
    Location
    Mashin' on the motorway
    Posts
    8,169
    I love being predictable

    PS: If you've got a copy of VC++7 anywhere, try compiling your code and watch the warning messages
    I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
    -- Linus Torvalds

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width