Click to See Complete Forum and Search --> : Reading files


cassie
December 20th, 2001, 04:20 PM
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) and scrnid (col 243)
I would like to read in this file and assign a variable for each item read in. I am currently utilizing .get and .getline. Can someone suggest a way to target col 243 after col 31? Thanks in advance.

cassie

ravash5000
December 20th, 2001, 04:32 PM
The easiest way is to read that space in between into a variable(junk) and the cursor will be at the place where you want it, you can use seekg too but it has a lot of hassle.

Andreas Masur
December 20th, 2001, 04:52 PM
#include <vector>
#include <string>
#include <fstream>

using std::vector;
using std::string;
using std::ifstream;

const unsigned short cusLastNameOffset = 0;
const unsigned short cusFirstNameOffset = 15;
const unsigned short cusMidInitOffset = 30;
const unsigned short cusScrnIdOffset = 242;

void EraseSpaces(string *const pstrSource)
{
string::size_type pos = pstrSource->find_last_not_of(' ');
if((pos != string::npos) && (pos + 1 != string::npos))
pstrSource->erase(pos + 1);
}

int main()
{
string strLine;
vector<string> vecFirstName;
vector<string> vecLastName;
vector<string> vecMidInit;
vector<string> vecSrcnId;

// Open file
ifstream File("c:\\test.dat");
if(File->is_open() == true)
{
string strTemp;

while(getline(File, strLine))
{
// Last name
strTemp = strLine.substr(cusLastNameOffset, cusFirstNameOffset - cusLastNameOffset);
EraseSpaces(&strTemp);
vecLastName.push_back(strTemp);

// First name
strTemp.erase();
strTemp = strLine.substr(cusFirstNameOffset, cusMidInitOffset - cusFirstNameOffset);
EraseSpaces(&strTemp);
vecFirstName.push_back(strTemp);

// Mid init
strTemp.erase();
strTemp = strLine.substr(cusMidInitOffset, cusScrnIdOffset - cusMidInitOffset);
EraseSpaces(&strTemp);
vecMidInit.push_back(strTemp);

// Scrn Id
strTemp.erase();
strTemp = strLine.substr(cusSrcnIdOffset);
EraseSpaces(&strTemp);
vecSrcnId.push_back(strTemp);
}
}

// Close file
File.close();

return 0;
}




Ciao, Andreas

"Software is like sex, it's better when it's free." - Linus Torvalds