Solved

reading a text file into a structure

Posted on 1998-04-20
5
213 Views
Last Modified: 2010-04-10
I have a seemingly basic task that is eluding me. I need to read a text file into a structure in the format <company name>,<address>, <city,state,zip>. I also have some parts information that needs to go into a separate structure in the format <# of items on invoice>, <item name>,<item code #>, <item price>, <item quantity>. I can't find an example in my textbook (How to Program C++, 2nd ed., Deitel & Deitel). All the information is in a single text file in the order given. My compiler is MSVC++ 5.0. Thanks for any help I can get!!  
0
Comment
Question by:hwhipple
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
5 Comments
 
LVL 22

Expert Comment

by:nietod
ID: 1162386
What is the format of the text file?  What delimits the differnet fields?  That is how can you tell the address from the company name?  What is the format of the structures  How long ar these strings or can they be any length?
0
 
LVL 4

Accepted Solution

by:
piano_boxer earned 50 total points
ID: 1162387
If every field (<company name>, <address>....) allways is separated by a comma, then you could read a single line of text into a local buffer, and extract the fields (tokens) one by one.

char* pToken;
char buf[1024];
FILE* pFile;

pFile = fopen("file.txt", "r");
if(pFile)
{
    while(fgets(buf, sizeof(buf), pFile))
    {
        pToken = strtok(buf, ",");
        while(pToken)
        {
            TRACE("Token found = %s\n", pToken);
            pToken = strtok(NULL, ",");
        }
    }
    fclose(pFile);
}
   


0
 
LVL 10

Expert Comment

by:RONSLOW
ID: 1162388
I have a sample app for reading comma separated values from a file and displaying etc.

The key routine is

CString GetField(CString& ref, int nIndex, TCHAR ch = _T(','))
{
  CString strReturn;
  LPCTSTR pstrStart = ref.LockBuffer();
  LPCTSTR pstrBuffer = pstrStart;
  int nCurrent = 0;
  int nStart = 0;
  int nEnd = 0;
  int nOldStart = 0;
  while (nCurrent <= nIndex && *pstrBuffer != _T('\0'))
  {
    if (*pstrBuffer == ch)
    {
      nOldStart = nStart;
      nStart = nEnd+1;
      nCurrent++;
    }
    nEnd++;
    pstrBuffer++;
  }
  ref.UnlockBuffer();
  if (*pstrBuffer == _T('\0'))
  {
    TRACE("Warning: Couldn't find it.\n");
    return strReturn;
  }
  return ref.Mid(nOldStart, nEnd-nOldStart-1);
}

this extract a given field (by field number) from the string.

For points I could send you the full sample code :-)
0
 
LVL 5

Expert Comment

by:yonat
ID: 1162389
Take a look at http://www.snippets.org/STRUCFIL.H and http://www.snippets.org/STRUCFIL.C and see if this is what you are loong for.
0
 

Expert Comment

by:manuel_99
ID: 12235266
Hello I'm new here, I having problem reading a text file. it looks like this:
Peter,sydney australia,1223
I know how to open the file and read the lines, but how can I separate the values that are text delimited and put them into an array?
//My struc look like this
struct Sighting{
      string firstName;
      string city;
      int postcode;
};

//this is the body
  file1.open("textfile.txt");
  if (file1.fail())
  {
        cout<<"File Open Error";
        exit(-1);
  }
  int i=0;
  while(!file1.eof())
  {
        getFileEntry(file1,p1[i]);
        i++;
  }

  for (int j=0; j<i-1; j++)
  {
          displayEntry(p1[j]);
  }
file1.close();
 }
void getFileEntry(ifstream &infile, Sighting &anEntry)
{
      infile>>anEntry.firstName;
      infile>>anEntry.surName;
      infile>>anEntry.extension;
}
//display
void displayEntry(Sighting anEntry)
{
cout << setw(20) << anEntry.firstName << setw(20) << anEntry.surName << " ";
cout << setw(4) << setfill('0') << anEntry.extension << setfill(' ') << endl;
}

// function to sort an array of Phone Entries into descending order
void selectionSortStruct(Sighting entryArray[], int length){
}
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Lambda for random numbers problem 7 120
Unresolved External Symbols 3 128
Safe conversion? 4 75
Can Live bindings change TGrid Cell Colour ? 1 30
When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
This article will show you some of the more useful Standard Template Library (STL) algorithms through the use of working examples.  You will learn about how these algorithms fit into the STL architecture, how they work with STL containers, and why t…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question