list implemetation in C++ STL

Hey Experts,

I am novice to STL. can anyone pls help me in understanding how to create a list from an input file.
for example say we have a input file having employees name on our disk. How can we use this file to create a list of name?

Thanks for your help.

Ruchi
1
2
3
4
5
6
7
8
9
std::list< std::string >    employeenames;
std::string name;

while( /* loop until EOF */ )
{
  // ... read one name from the file, store it in 'name'

  employeenames.push_back( name );
}
Thanks Disch,

I will try it.
Hopefully, the OP understands that list is a specific kind of STL container. Sometimes people use the word list in a more general sense. It doesn't mean that you need the list from the STL. There are many kinds of containers and the suitability of each depends on what you plan on doing with the data once it is read from the file.
http://cplusplus.com/reference/stl/
I tend to prefer a std::deque for text file data...
1
2
3
ifstream in("file.txt");
istream_iterator<string> in_it(in), eof;
list<string> employees(in_it, eof);


also works...
You'll have to #include <iterator> to use felipe21's answer.
Also, the input will be whitespace-separated words, not lines.
Last edited on

Also, the input will be whitespace-separated words, not lines


True. I forgot that. Can we override the field separator?
Not directly, but I will tend to write a little class to do it for me:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// reverse.cpp
//
// Reverse the order of lines in an input file.
// For example, 
//   one             three
//   two      -->    two
//   three           one
//

#include <algorithm>
#include <deque>
#include <iostream>
#include <iterator>
#include <string>
using namespace std;

struct textline_t: public string { };

inline istream& operator >> ( istream& ins, textline_t& s )
  {
  return getline( ins, s );
  }

int main()
  {
  typedef deque <string> lines_t;

  lines_t lines;

  copy(
    istream_iterator <textline_t> ( cin ),
    istream_iterator <textline_t> (),
    back_insert_iterator <lines_t> ( lines )
    );

  copy(
    lines.rbegin(),
    lines.rend(),
    ostream_iterator <string> ( cout, "\n" )
    );

  return 0;
  }


Now you can have fun:

reverse < reverse.cpp

and

reverse < reverse.cpp | reverse

Heh heh heh...
Topic archived. No new replies allowed.