The Database Managers, Inc.

Contact The Database Managers, Inc.


Use an RSS enabled news reader to read these articles.Use an RSS enabled news reader to read these articles.

Reading a text file into an STL vector of strings

by Curtis Krauskopf

Q:  I need to read a text file into an STL vector of strings.

A:  Here's an example:

#include <string>
#include <vector>
#include <fstream>
#include <iostream>

#pragma hdrstop

// Read a file into a vector

void help(char *program) {
  std::cout << program; 
  std::cout << ": Need a filename for a parameter.\n";
}

int main(int argc, char* argv[])
{
  if (argc < 2) { help(argv[0]); return 1; }
  std::vector<std::string> file;
  std::string line;
  file.clear();
  std::ifstream infile (argv[1], std::ios_base::in);
  while (getline(infile, line, '\n'))
  {
    file.push_back (line);
  }

  std::cout << "Read " << file.size() << " lines.\n";

  return 0;
}


Output:

> example example.cpp
Read 29 lines.

This article was written by Curtis Krauskopf (email at ).

Popular C++ topics at The Database Managers:

C++ FAQ Services | Programming | Contact Us | Recent Updates
Send feedback to: