【问题标题】:C++ Reading text file, storing objects and printing out array [closed]C ++读取文本文件,存储对象并打印出数组[关闭]
【发布时间】:2015-05-01 12:27:42
【问题描述】:

我正在读取一个带有制表符分隔的名字、姓氏和邮政编码的输入文件。其中有 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

请帮忙!!

【问题讨论】:

  • 向我们展示persons的声明。
  • 对不起,这里是: // 数组声明 Person* 个人[25];

标签: c++ arrays file pointers


【解决方案1】:

问题是,您只需要一个循环。这将读取最多 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;
    }
}

【讨论】:

  • 好答案。我可能会在阅读输入后添加一些检查以确保阅读了 25 个人。 OP 似乎没有跟踪数组的实际大小,所以听起来像是 25 或半身像。在这种情况下,#define N 25 会很有用,可以阻止复制幻数。
  • 这项工作。谢谢你。我对 C++ 真的很陌生。这是第一个实验室。我会继续努力的。
猜你喜欢
  • 1970-01-01
  • 2021-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多