TIP: Click on subject to list as thread! ANSI
echo: c_plusplus
to: ROY LEBLANC
from: THOMAS MAEDER
date: 1997-12-06 11:47:00
subject: Parsing a file

RL> Could some one tell me how I can use C++ to input a line
RL> of ASCII-delimited text from a file and parse it into an
RL> array/structure/structured array(?)?
RL>  A typical line might look like:
RL>  "89765B","William","McIntire","70501",724,2,27.85
So your structure looks something like this, I assume:
struct Person { 
    string Id; 
    string FirstName;
    string LastName;
    string aString;
    unsigned int anInt;
    unsigned int anotherInt;
    double aDouble;
};
And what you want to write is:
Person aPerson;
iasciistream inFile("filename");
if (inFile >> aPerson)
    // reading was a success, use aPerson
else
    // oops
iasciistream is a class you have to derive from istream. Overload  the
operator>>  for string, int, double and maybe other types according to
your file structure (input operations have to eat the  commas,  string
input also the quotes).
Now you can overload operator>> for Person:
iasciistream &operator>>(iasciistream &ias, Person &aPerson)
{
    return  ias >> aPerson.Id 
                >> aPerson.FirstName 
                >> aPerson.LastName
                >> aPerson.aString
                >> aPerson.anInt
                >> aPerson.anotherInt
                >> aPerson.aDouble;
}
If  you  need  other  ways  of  reading  a Person, you might make this
operator a template:
template 
istram_type &operator>>(istream_type &is, Person &aPerson)
{
    return   is >> aPerson.Id 
                >> aPerson.FirstName 
                >> aPerson.LastName
                >> aPerson.aString
                >> aPerson.anInt
                >> aPerson.anotherInt
                >> aPerson.aDouble;
}
Thomas
---
 þ MM 1.0 #0113 þ I t±ld yo±, "Never±touch ±he flop±y disk s±rface!"
---------------
* Origin: McMeier & Son BBS (2:301/138)

SOURCE: echomail via exec-pc

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.