Uploading Vector To File
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: Uploading Vector To File

  1. #1
    Join Date
    Dec 2003
    Posts
    10

    Uploading Vector To File

    I am now using Dev-C++ 4, and am trying to upload my vector elements using the infile as I did with VC4, but I do realize that they are not the same.

    Code:
    #include <fstream>
    #include <vector>
    #include <string>
    #include <stdlib.h>
    
    int main()
    {
      // dcelare variables
      ifstream infile;
      std::vector <string> username;
      username.reserve(100);
      short index;
    
      // get usernames from file
      infile.open("user_db.dat", ios::in);
      index = username.size();
      do
      {
        index--;
        infile >> username[index];
      }
      while(index != 0);
    
      infile.close();
      system("PAUSE");
      return 0;
    }
    It compiles right, but I get an error when running it saying it has performed an illegal operation and closes. Any help?

    JDM

  2. #2
    Join Date
    Apr 1999
    Posts
    27,423

    Re: Uploading Vector To File

    Originally posted by lifeofjdm
    I am now using Dev-C++ 4, and am trying to upload my vector elements using the infile as I did with VC4, but I do realize that they are not the same.
    Code:
      username.reserve(100);
      //....
       infile >> username[index];  // illegal operation
    The vector is empty, and you are trying to access a non-existing element. You are lucky it doesn't crash in VC 4.0.

    No, reserve() does not add elements to the vector, resize() does.

    The reserve function only gives the vector more memory up front so that operations such as push_back() are more efficient. The reserve() does not actually give you more elements.
    Code:
      username.resize(100);  
      //....
       infile >> username[index];  // OK if index is between 0 and 99, inclusive
    Regards,

    Paul McKenzie

  3. #3
    Join Date
    Dec 2003
    Posts
    10
    Thank you very much! ...

    JDM

Posting Permissions

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


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center