我在输入文件中读取带有制表符分隔的名字,姓氏和邮政编码。其中有25个。我试图将其读入,将其存储到对象中并再次打印出来。
以下是代码:
// Reading in from an input file
ifstream inputFile("nameInput.txt");
string line;
for(int i = 0; i<25; i++){
while (getline(inputFile, line))
{
istringstream getInput(line);
string tempFName, tempLName;
int tempZip;
getInput >> tempFName >> tempLName >> tempZip;
// Creating new Person objects with the data
persons[i] = new Person(tempFName, tempLName, tempZip);
}
inputFile.close();
// Printing out String representation of the Person
persons[i]->toString();
}
在编译时,在运行期间这是我得到的错误:87023
分段错误:11
请帮助!!
答案 0 :(得分:2)
问题是,你只需要一个循环。这将最多读取25行:
int main()
{
const int n_persons = 25;
std::shared_ptr<Person> persons[n_persons];
std::ifstream inputFile("nameInput.txt");
std::string line;
for(int i = 0; i < n_persons && std::getline(inputFile, line); ++i)
{
std::istringstream getInput(line);
std::string tempFName, tempLName;
int tempZip;
if(getInput >> tempFName >> tempLName >> tempZip)
{
// Creating new Person objects with the data
persons[i] = new Person(tempFName, tempLName, tempZip);
// Printing out string representation of the Person
persons[i]->toString();
}
else
cout << "error on line #" << i + 1 << " occurred" << endl;
}
}