• Advertisement
Sign in to follow this  

Reading in a data file

This topic is 4649 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
Advertisement
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,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
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
Sign in to follow this  

  • Advertisement