Sign in to follow this  
Jankos

Reading Delimited Files

Recommended Posts

I was wondering how i could read in comma delimited things from file. I have this in a file: 1,Start,You Are Standing In The Starting Room 2,Secod,You Are Standing In The Second Room how would i read that in to a class called room with the members variables: int roomid; string name; string desc; or just read it into the program period? Any help with this would be appreciated!

Share this post


Link to post
Share on other sites
Assuming you're using C++, you could do something like this:
std::cin >> roomid;
std::cin.ignore(1,',');
std::getline(cin,name,',');
std::getline(cin,desc,',');


Feel free to look up some documentation for this - I don't do much C++ these days :)

EDIT: Doh! Of course, my code reads from stdin - you should change cin to the istream object you've created.

Share this post


Link to post
Share on other sites
if you overload the stream insertion/extraction operators then you can make reading rooms into containers simple with stream iterators:


#include <algorithm> // replace
#include <string>
#include <istream>
#include <ostream>
#include <sstream>

template < typename CharT, typename Traits = std::char_traits<CharT>, typename Alloc = std::allocator<CharT> >
struct room {

typedef std::basic_string<CharT, Traits, Alloc> string_type;

int roomid;
string_type name;
string_type desc;

};

template < typename CharT, typename Traits, typename Alloc >
std::basic_istream<CharT, Traits>& operator>>(std::basic_istream<CharT, Traits>& in, room<CharT, Traits, Alloc>& r) {

typedef std::basic_istringstream<CharT, Traits, Alloc> istrstream;
typedef typename room<CharT, Traits, Alloc>::string_type string_type;

string_type s;

std::getline(in, s);

std::replace(s.begin(), s.end(), CharT(','), CharT(' '));

istrstream ss(s);

ss >> r.roomid >> r.name;

return std::getline(ss, r.desc);
}

template < typename CharT, typename Traits, typename Alloc >
std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& out, const room<CharT, Traits, Alloc>& r) {
return (out << r.roomid << CharT(' ') << r.name << CharT(' ') << r.desc << std::endl);
}



example:


#include <iterator> // istream_iterator, ostream_iterator
#include <vector>
#include <fstream>
#include <iostream>

int main() {

typedef room<char> room_type;

typedef std::vector<room_type> vec_of_rooms;

std::ifstream ifs("temp.txt");

vec_of_rooms v((std::istream_iterator<room_type>(ifs)),
std::istream_iterator<room_type>());

std::copy(v.begin(), v.end(),
std::ostream_iterator<room_type>(std::cout));

}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this