I'm having troubles opening the my text file in this bit of code. Am I doing it the correct way? Just started C++ this week.
I'm having troubles writing to the output file now. The only output I'm getting is this. libc++abi.dylib: terminating with uncaught exception of type std::invalid_argument: stoi: no conversion (lldb)
Thanks in advance guys.
Here is my employeesIn.txt
<123>,<John>,<Brown>,<125 Prarie Street>,<Staunton>,<IL>,<62088>
<124>,<Matt>,<Larson>,<126 Hudson Road>,<Edwardsville>,<IL>,<62025>
<125>,<Joe>,<Baratta>,<1542 Elizabeth Road>,<Highland>,<IL>,<62088>
<126>,<Kristin>,<Killebrew>,<123 Prewitt Drive>,<Alton>,<IL>,<62026>
<127>,<Tyrone>,<Meyer>,<street>,<999 Orchard Lane>,<Livingston>,<62088>
And here is my code
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
struct Person {
string first;
string last;
};
struct Address {
string street;
string city;
string state;
string zipcode;
};
struct Employee {
Person name;
Address homeAddress;
int eid;
};
void readEmployee(istream& in, Employee& e);
void displayEmployee(ostream& out, const Employee& e);
int main(int argc, const char * argv[])
{
Employee e[50];
ifstream fin;
ofstream fout;
fin.open("employeesIn.txt");
if (!fin.is_open()) {
cerr << "Error opening employeesIn.txt for reading." << endl;
exit(1);
}
fout.open("employeesOut.txt");
if (!fout.is_open()) {
cerr << "Error opening employeesOut.txt for writing." << endl;
exit(1);
}
int EmployeePopulation = 0;
readEmployee(fin, e[EmployeePopulation]);
while (!fin.eof()) {
EmployeePopulation++;
readEmployee(fin, e[EmployeePopulation]);
}
fin.close();
for (int i = 0; i <= EmployeePopulation - 1; i++) {
displayEmployee(fout, e[i]);
}
fout.close();
cout << endl;
return 0;
}
void readEmployee(istream& in, Employee& e)
{
string eidText;
if ( getline(in, eidText, ',') ) {
e.eid = stoi(eidText);
getline(in, e.name.first, ',');
getline(in, e.name.last, ',');
getline(in, e.homeAddress.street, ',');
getline(in, e.homeAddress.city, ',');
getline(in, e.homeAddress.state, ',');
string zipcodeText;
getline(in, zipcodeText, ',');
e.homeAddress.zipcode = stoi(zipcodeText);
}
}
void displayEmployee(ostream& out, const Employee& e)
{
out << "Customer Record: " << e.eid
<< endl
<< "Name: " << e.name.first << " " << e.name.last
<< endl
<< "Home address: " << e.homeAddress.street
<< endl
<< e.homeAddress.city << ", " << e.homeAddress.state << " " << e.homeAddress.zipcode
<< endl
<< endl
<< endl;
}