Thread: iFstream_iterator???

  1. #1
    Registered User
    Join Date
    Feb 2003
    Posts
    265

    iFstream_iterator???

    ok, there is an istream_iterator like istream_iterator<int>(cin). what i need is an ifstream_iterator for a file like istream_iterator<int>(datafile). my code works when cin is used, however failes when i try to use a datafile. if anybody knows of a nifty trick to convert a class std::basic_ifstream<char,struct std::char_traits<char> to a class std::basic_istream<char,struct std::char_traits<char> >, so i can use a istream_iterator with a converted ifstream object, or an ifstream iterator (i checked and didnt see one) im very interested in hearing about it. thanks.

  2. #2
    Registered User
    Join Date
    Jul 2003
    Posts
    11
    Works for me like this
    Code:
    #include <iostream>
    #include <fstream>
    #include <iterator>
    
    using namespace std;
    
    int main()
    {
        ifstream ifs("in.txt");
        istream_iterator<char> ii(ifs);
        
        while (ifs)
            cout<< *ii++;
    }
    An ifstream is an istream, so you shouldn't be having any problems unless you're doing it wrong.

  3. #3
    Registered User
    Join Date
    Feb 2003
    Posts
    265
    #include <iterator>
    #include <vector>
    #include <iostream>
    #include <fstream>
    int main()
    {
    string filename = "test.txt";
    std::ifstream datafile;
    datafile.open(filename.c_str());
    vector<int> bobs;
    copy( (istream_iterator<int> (datafile)),istream_iterator<int>(),back_inserter( bobs));
    return 0;
    }

    The vector bobs is left empty after this code executes. This is a scaled down example of how im trying to load the data.

  4. #4
    Registered User
    Join Date
    Jul 2003
    Posts
    11
    Code:
    #include <iterator>
    #include <vector>
    #include <iostream>
    #include <fstream>
    #include <algorithm>
    
    using namespace std;
    
    int main()
    {
        ifstream datafile("test.txt");
        vector<int> bobs;
    
        copy(istream_iterator<int>(datafile),istream_iterator<int>(),back_inserter(bobs));
        copy(bobs.begin(), bobs.end(), ostream_iterator<int>(cout, " "));
    
        return 0;
    }
    I'm really not having any problems with it. What compiler do you use? Perhaps the stream iterators aren't well written on your compiler, mine is Visual C++ 6.0.

  5. #5
    Registered User
    Join Date
    Feb 2003
    Posts
    265
    MSFT VC++ 6.0 on win2k. Its been having trouble with iterators all day. im starting to think its time for a reinstall. Seems like code that works fine with others doesnt work with mine. I dont believe i added or removed any libs recently. this is odd.

Popular pages Recent additions subscribe to a feed