CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: Reading files

  1. #1
    Join Date
    Dec 1999
    Posts
    1

    Reading files

    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


  2. #2
    Join Date
    Jun 2001
    Location
    LoS AnGeLeS
    Posts
    251

    Re: Reading files

    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.


  3. #3
    Join Date
    May 2000
    Location
    KY, USA
    Posts
    18,652

    Re: Reading files


    #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

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured