Thread: vector??

  1. #1
    Registered User
    Join Date
    Jun 2005
    Posts
    47

    vector??

    can someone show me how to use vector to read .txt files.

  2. #2
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    The simple way to do this but avoid istream_iterators is to read a line with std::getline into a std::string then simply push_back that string into a std::vector.Do that in a loop until you have nothing left in the file.
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

  3. #3
    aoeuhtns
    Join Date
    Jul 2005
    Posts
    581
    Better yet, push back an empty string and getline into that string.

  4. #4
    Banned
    Join Date
    Jun 2005
    Posts
    594
    Code:
    fstream file;
    string fS;
    vector<string> vS;
    file.open("in.txt", ios::in);
    while(!file.eof())
    {
         getline(file, fS, '\n');
         vS.push_back(fS);
    }

  5. #5
    Weak. dra's Avatar
    Join Date
    Apr 2005
    Posts
    166
    It's not a good thing to use eof() to control a loop.

    Code:
    fstream file;
    string fS;
    vector<string> vS;
    file.open("in.txt", ios::in);
    while(getline(file, fS, '\n'))
    {
         vS.push_back(fS);
    }
    does the same thing. i think...

  6. #6
    Sweet
    Join Date
    Aug 2002
    Location
    Tucson, Arizona
    Posts
    1,820
    It sure does. And the reason is that eof is not set until you pass the end of file so it is safer to read until you reading fails.
    Woop?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. can some one please tell me the cause of the error ?
    By broli86 in forum C Programming
    Replies: 8
    Last Post: 06-26-2008, 08:36 PM
  2. syntax help?
    By scoobygoo in forum C++ Programming
    Replies: 1
    Last Post: 08-07-2007, 10:38 AM
  3. Vector class
    By Desolation in forum C++ Programming
    Replies: 2
    Last Post: 05-12-2007, 05:44 PM
  4. Need some help/advise for Public/Private classes
    By nirali35 in forum C++ Programming
    Replies: 8
    Last Post: 09-23-2006, 12:34 PM
  5. Certain functions
    By Lurker in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2003, 01:26 AM