Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Reading in an external file and assigning each part to a variable.

Status
Not open for further replies.

cassie99

Programmer
Dec 20, 2001
26
US
Hi,

Please bear with me, I have very little experience with C++. I have an external .dat file with a defined format. e.g. lastname (cols 1-15), firstname (cols 16-30), mid_init (col 31), etc...
I would like to read in this file and assign a variable for each item read in. Can someone get me started with this? Thanks in advance.

cassie
 
Code:
#include <fstream.h>

void main()
{
   ifstream in(&quot;input.txt&quot;);
   
   char lName[15];
   char fName[15];
   char mi;
 

   in.getline(lName,15);
   in.getline(fName,15);
   in.get(mi);

}

That should get you headed down the right path. fstream stands for file stream and ifstream is an input file stream.

Good luck

matt
 
Thanks for the starter code. I neglected to ask how I can access screen id information in the file that always resides in column 243. e.g lastname (cols 1-15), firstname (cols 16-30), mid_init (col 31), scrnid (col 243). Thanks in advance.

cassie
 
Take Zyrenthian's example and add a &quot;dummy&quot; input variable to offet the input to what you need.

Also I think there's a small bug... be sure to add one to each allocation in his program for the NULL character:


#include <fstream.h>

void main()
{
ifstream in(&quot;input.txt&quot;);

char lName[16];
char fName[16];
char mi;
char sDummy[212];
char sScreenID[11];

in.getline(lName,15);
in.getline(fName,15);
in.get(mi);

/* you don't care about this info */
in.getline(sDummy,211);

/* so far we've read in 242 characters */
/* the next ones are what you want, but */
/* read the correct number of chars and */
/* change the allocation above (+ 1) */
in.getline(sScreenID,10);
}

 
Ooops, I guess you specified that the screen ID was only a single character, so change the allocation and the getline to:

char sScreenID;

in.get(sScreenID);

p.s.
Also, that word in the first sentence of the previous post should be &quot;offset&quot;.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top