我正在尝试使我的代码能够将文件分隔到客户数据库中(它由许多空格而不是制表符分隔)。我尝试使用 strtok,但出现 EXC_BAD_ACCESS 错误。这是我的 main.cpp 代码:
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include "Cust.h"
using namespace std;
int main (int argc, char * const argv[]) {
Cust customers[500];
int idx = 0;
string tmpString = "";
string tmpAcctFN = "";
string tmpAcctLN = "";
ifstream input("P3_custData.txt");
while (!input.eof()){
getline(input,tmpString);
tmpString.insert(0,"");
customers[idx].setAcctNum(atoi(strtok((char *)tmpString.c_str()," ")));
customers[idx].setAcctFN(strtok(NULL," "));
customers[idx].setAcctLN(strtok(NULL," "));
//customers[idx].setCurrBalance(atof(strtok((char *) tmpString.c_str()," ")));
}
cout << "return 0;";
return 0;
}
根据评论进行更改后,我仍然得到 EXC_BAD_ACCESS:
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include "Cust.h"
using namespace std;
int main (int argc, char * const argv[]) {
Cust customers[500];
int idx = 0;
string tmpString = "";
string tmpAcctFN = "";
string tmpAcctLN = "";
char * s;
ifstream input("P3_custData.txt");
while (!input.eof()){
getline(input,tmpString);
s = strdup (tmpString.c_str());
customers[idx].setAcctNum(atoi(strtok(s," ")));
customers[idx].setAcctFN(strtok(NULL," "));
customers[idx].setAcctLN(strtok(NULL," "));
//customers[idx].setCurrBalance(atof(strtok((char *) tmpString.c_str()," ")));
}
cout << "return 0;";
return 0;
}