【发布时间】:2014-09-05 15:47:42
【问题描述】:
我以为我已经完全解决了这个问题,但实际上并没有向文件写入任何内容。它正在打开 employeesOut.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
libc++abi.dylib:以 std::invalid_argument 类型的未捕获异常终止:stoi:无转换 (lldb)
我相信错误在我的 main.cpp 中,所以就是这样。
#include <iostream>
#include <string>
#include <fstream>
#include "Employee.h"
using namespace std;
bool openFileForReading(ifstream& fin, const string& filename);
bool openFileForWriting(ofstream& fout, const string& filename);
int readFromFile(ifstream& in, Employee empArray[]);
void writeToFile(ofstream& out, const Employee empArray[], const int numberofEmployees);
int main(){
ifstream fin;
ofstream fout;
if(!openFileForReading(fin, "employeesIn.txt")) {
cerr << "Error opening employeesIn.txt for reading." << endl;
exit(1);
}
if(!openFileForWriting(fout, "employeesOut.txt")) {
cerr << "Error opeing employeesOut.txt for writing." << endl;
exit(1);
}
Employee employeeArray[50];
int employeeCount = readFromFile(fin, employeeArray);
fin.close();
writeToFile(fout, employeeArray, employeeCount);
fout.close();
cout << "Program successful." << endl << endl;
return 0;
}
bool openFileForReading(ifstream& fin, const string& filename) {
fin.open("employeesIn.txt");
return (fin.is_open());
}
bool openFileForWriting(ofstream& fout, const string& filename) {
fout.open("employeesOut.txt");
return (fout.is_open());
}
int readFromFile(ifstream& in, Employee empArray[]) {
int temp = 0;
string eidText;
string first;
string last;
string street;
string city;
string state;
string zipcode;
while(!in.eof()) {
getline(in, eidText, ',');
getline(in, first, ',');
getline(in, last, ',');
getline(in, street, ',');
getline(in, city, ',');
getline(in, state, ',');
getline(in, zipcode, ',');
empArray[temp].setEid(stoi(eidText));
empArray[temp].setName(first, last);
empArray[temp].setAddress(street, city, state, zipcode);
temp++;
}
return temp;
}
void writeToFile(ofstream& out, const Employee empArray[], const int numberOfEmployees) {
for (int i = 0; i < numberOfEmployees; i++){
out << "Employee Record: " << empArray[i].getEid()
<< endl
<< "Name: " << empArray[i].getName()
<< endl
<< "Home Address: " << empArray[i].getAddress()
<< endl
<< endl;
}
}
【问题讨论】:
-
你能发布你作为输入的文件的前几行吗?
-
为什么要使用自己的函数打开文件而不是直接使用流方法?看起来有点浪费功能。
-
你的文件打开函数没有使用它们的参数,所以去掉参数。
-
当您使用调试器时,哪个语句导致了问题?您是否在写入前尝试打印数据?
-
我已将输入文件添加到上述帖子中。
标签: c++ file-io output ostream