I'm reading from a file that is using fixed length entries:
And, i have to rewrite the (>>) operator to read the fixed length fields.Code:Will Smith 25 Place Tulsa OK 38135 Corey Black Elm Street Dallas TX 89148 Tanner Hall Mount View Denver CO 52742
My code:
So, i want the first 11 characters (including spaces) to be read into first name, the next 11 into last name and so on. For some reason they are not being read in correctly. The output looks like:Code:#include <iostream> #include <fstream> #include <string> using namespace std; class Person { public: char FirstName [11]; char LastName[11]; char Address [16]; char City [16]; char State [3]; char ZipCode [10]; Person(); }; Person::Person() { LastName[0] = 0; FirstName[0] = 0; Address[0] = 0; City[0] = 0; State[0] = 0; ZipCode[0] = 0; } ostream & operator << (ostream & stream, Person & p) { stream << "First Name :" << p.FirstName << endl; stream << "Last Name :" << p.LastName << endl; stream << "Address :" << p.Address << endl; stream << "City :" << p.City << endl; stream << "State :" << p.State << endl; stream << "ZipCode :" << p.ZipCode << endl; stream << flush; return stream; } istream & operator >> (istream & stream, Person & p) { stream.get(p.FirstName, 11); stream.get(p.LastName, 11); stream.get(p.Address, 16); stream.get(p.City, 16); stream.get(p.State, 3); stream.get(p.ZipCode, 10); return stream; } int main() { fstream inFile; inFile.open("fixedlength.txt"); Person person1; inFile >> person1; cout << person1; cout << endl; cout << endl; cout << person1.FirstName << "Test" << endl; cout << person1.LastName << "Test" << endl; cout << person1.Address << "Test" << endl; cout << person1.City << "Test" << endl; cout << person1.State << "Test" << endl; cout << person1.ZipCode << "Test" << endl; cout << endl; cin.get(); cout << endl; return 0; }
As you can see, the spacing is messed up. The amount of spacing on the first name entry is 10 instead of 11 (one missing space). So, it looks like this space is being read into the next entry (last name), and that is why there is a space before smith. If i increase:Code:First Name :Will Last Name : Smith Address : 25 Place City : Tulsa State : ZipCode : OK 3813 Will Test Smith Test 25 Place Test Tulsa Test Test OK 3813Test
the output is even more messed up.Code:stream.get(p.FirstName, 11); to stream.get(p.FirstName, 12);
I originally tried:
but it wouldn't read in the spaces. Added stream >> noskipws; to that, and it didn't work right.Code:stream >> p.FirstName; stream >> p.LastName; stream >> p.Address; stream >> p.City; stream >> p.State; stream >> p.ZipCode;
Basically i want to force it to read in the fixed amount, even if the characters are spaces.
Thanks.



LinkBack URL
About LinkBacks


