2015-05-01 34 views
-4

我正在用制表符分隔的名字,姓氏和邮政编码阅读输入文件。其中有25个。我正在尝试读取它,将其存储到对象中并再次打印出来。C++读取文本文件,存储对象并打印输出数组

下面的代码:

// 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

向我们展示'persons'的声明。 – LogicStuff

+0

对不起,这里是:\t //数组声明 \t人*人[25]; – swati

回答

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; 
    } 
} 
+1

很好的答案。我可能会在阅读输入后添加一些检查以确保有25人被阅读。 OP似乎没有跟踪数组的实际大小,所以它听起来像是25或者是萧条。在这种情况下,#define N 25会很有用,可以阻止复制一个幻数。 – AndyG

+0

这项工作。谢谢。我对C++非常陌生。这是第一个实验室。我会继续努力。 – swati

相关问题