我在这段代码中打开我的文本文件时遇到了麻烦。我这样做是正确的吗?本周刚刚开始使用C ++。
我现在正在写输出文件时遇到麻烦。我得到的唯一输出就是这个。 libc ++ abi.dylib:以std :: invalid_argument类型的未捕获异常终止:stoi:无转换 (lldb)
先谢谢你们。
这是我的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>
这是我的代码
#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;
}
答案 0 :(得分:3)
正是它所说的:stoi
失败了。
您只有两次,所以很明显您的eidText
不是数字,或者您的邮政编码不是数字。
我们不知道这是由于输入文件的问题还是解析问题,因此在eidText
之前将zipcodeText
和stoi
输出到控制台,你可以看到他们的价值观,然后继续相应的诊断。