写入文件后,信息最终出现在控制台中

时间:2018-11-25 09:16:56

标签: c++ arrays oop methods

这是一个项目,我需要在其中列出用户要输入的项目列表,并且需要将它们写入文件中。但是,它为其中的每个条目打印@4761920nan。然后,它将所有应该在控制台文件中的内容打印出来。对这个问题的任何看法将不胜感激。

int main()
{
    ofstream data("list.txt");
    int n;
    cout << "How many cabins are in your region? "; cin >> n; cout<<endl;
       cabin*tour=
     new cabin[n];

    for (int i=0; i<n; i++)
    {
        tour[i].nameInput();
        data<<tour[i].nameOutput();
        tour[i].capacity();
        data<<tour[i].capacityOutput();
        tour[i].gps();
        data<<tour[i].gpsOutput();
    };

    data.close();
    return 0;
}

nameOutput()如下所示:

char cabin::nameOutput()
{
    cout<<"Name: "<< name<<endl;
}

1 个答案:

答案 0 :(得分:1)

您的函数cabin::nameOutput的返回类型为char,但不返回任何内容。因此,呼叫

data << tour[i].nameOutput();

将适当地写入标准输出(由于cout),而不适当地写入data。由于什么都不会返回,因此写入data的输出是不确定的行为。

为了解决此问题,您可能希望像这样在函数中指定返回类型

// the return type depends on the type of `name`
// this may be char*, std::string, or something else appropriate
std::string cabin::nameOutput()
{
    cout << "Name: " << name << endl;
    return name;
}