reading line by line from txt file

Pages: 12
Here's something similar that works.


input File:
Tommy$Gunn
Bobby$Smither
William$Hammet
Shenna$North
Robert$Stillskin
Walter$Mellon


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
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

struct Name
{
    std::string first ;
    std::string last ;
};

std::ifstream & read_name( std::ifstream& in, Name& name )
{
    std::getline( in, name.first, '$' ) ;
    std::getline( in, name.last ) ;
    return in ;
}

std::ostream& display( std::ostream& out, const Name& name )
{
    return out << name.last << ", " << name.first ;
}

int main()
{
    std::vector<Name> names ;

    std::ifstream file("names.txt") ;

    Name input ;

    while ( read_name(file, input) )
        names.push_back(input) ;

    std::cout << names.size() << " names read in.\n" ;

    for ( unsigned i = 0 ; i < names.size() ;  ++i )
        display(std::cout, names[i]) << '\n' ;
}
Topic archived. No new replies allowed.
Pages: 12