| 12
 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
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 
 | #include <vector>    // std::vector<>
#include <string>    // std::string
#include <sstream>   // std::istringstream
#include <algorithm> // std::copy
#include <iterator>  // std::ostream_iterator
#include <iostream>  
 
using namespace std;
 
struct A
{
    string nom;
    string prenom;
    string rue;
    string num_rue;
    string ville;
    string pays;
 
    vector <string> tab_comptes;
 
    void swap(A & other)
    {
        nom.swap(other.nom);
        prenom.swap(other.prenom);
        rue.swap(other.rue);
        num_rue.swap(other.num_rue);
        ville.swap(other.ville);
        pays.swap(other.pays);
        tab_comptes.swap(other.tab_comptes);
    }
}; 
 
std::ostream & operator<<(std::ostream & os, const A & v)
{
    os << v.nom << " " << v.prenom
        << "  habite au " << v.num_rue << ", " << v.rue
        << " " << v.ville << "(" << v.pays << ") --- "; 
    copy(v.tab_comptes.begin(),v.tab_comptes.end(),
            ostream_iterator<string>(os, ", "));
    return os;
}
 
istream & operator>>(istream & is, A & a)
{
    string ligne;
    if (getline(is,ligne)) {
        istringstream iss(ligne);
        A tmp;
        if (getline(iss,tmp.nom,';') && getline(iss,tmp.prenom,';')
                 && getline(iss,tmp.rue,';') && getline(iss,tmp.num_rue,';')
                 && getline(iss,tmp.ville,';') && getline(iss,tmp.pays,';'))
        {
            string cpt;
            while (getline(iss, cpt, ';')) {
                tmp.tab_comptes.push_back(cpt);
            }
            // éventuellement vérifier que les numéros de compte sont OK
            // et qu'il y a des comptes.
            a.swap(tmp);
        } else {
            std::cerr << "ERREUR: Entrée incorrecte: " << ligne << "\n";
            is.setstate(std::ios_base::failbit);
        }
    }
    return is;
}
 
 
void test(string const & fic)
{
    cout << fic << "\n";
    istringstream f(fic);
 
    A a;
    while (f >> a)
        std::cout << "---> " << a << "\n";
    if (!f.eof() && f.fail()) 
        std::cout << "Erreur!\n";
 
    cout << "\n------\n";
}
 
int main (int argc, char **argv)
{
    test("toto;titi;avenue truc;15;tlse;fr;1;2;42"
            "\ntata;tutu;rue chose;42;paris;fr;12;15;16");
    test("toto;titi;avenue truc;15;tlse;fr;1;2;42"
            "\ntata;tutu;rue chose;42;paris;fr;12;15;16\n");
    test("toto;titi;avenue truc;15;tlse;fr;1;2;42;5;6;8;9");
    test("toto;titi;avenue truc;15;tlse;fr;");
    test("toto;titi;avenue truc;15;tlse;fr");
    test("toto;titi;avenue truc;15;tlse;");
 
    std::cout << std::endl;
 
    return 0;
} | 
Partager