Sign in to follow this  
MTclip

Reading in a data file

Recommended Posts

MTclip    242
quick question ... if you are gonna load a file (text or binary ) what is the best method for that... I have not looked much in to it... but the only one i have used is fstream.... any others? (i am using c or c++******* ;P q;

Share this post


Link to post
Share on other sites
supercoder74    154
or use std::fstream!
its just like cin(and cout),because it is the same types!
lets say we have a file like this:

hello
my
name
is
bob



#include <fstream>
#include <iostream>
int main(int argc,char** argv)
{
fstream file("somefile.txt",std::in);//open file for input.
char lines[5][50];//the numbers in the file will be stored in here.
for(int i=0;!file.eof();i++)//read all numbers until the end of the file.
{
file.getline(lines[i],50);
}
cout<<lines[0]<<"<<lines[1]<<" "<<lines[2]<<" "<<lines[3]<<" "<<lines[4];
}


will output "hello my name is bob".

Share this post


Link to post
Share on other sites
snk_kid    1312
Quote:
Original post by supercoder74
or use std::fstream!
its just like cin(and cout),because it is the same types!


Not quite, how-ever they are sub-types of basic_i/o(io)stream so they are interchangeable where-ever there is a reference to those super types.

Quote:
Original post by supercoder74
lets say we have a file like this:
*** Source Snippet Removed ***
*** Source Snippet Removed ***
will output "hello my name is bob".


or more simply:


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

int main() {

typedef std::vector<std::string> vec_of_strs;
typedef std::istream_iterator<std::string> iss_itr;
typedef std::ostream_iterator<std::string> oss_itr;

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

vec_of_strs v((iss_itr(ifs)), iss_itr());

std::copy(v.begin(), v.end(), oss_itr(std::cout, " "));
}


We could make it less verbose with some boost lambda magic but thats another story...

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