1

I know the title is a little confusing, but I don't know how to explain it.

void save (POINT pt)
    {
    ofstream save;
    save.open("coords.txt", ios::trunc);

    if (save.is_open())
    {
        save << pt.x << endl;
        save << pt.y;

        save.close();

        system("CLS");

        cout << "Save successful\n\n\n\n";

        system("PAUSE");
    }

    else
    {
        system("CLS");

        cout << "Error: Could not save\n\n\n\n";

        system("PAUSE");
    }
    }

    int load ( )
    {
        ifstream load;
        load.open("coords.txt", ifstream::in);

        if (load.is_open())
        {

        }
    }

I want to read the POINT from the save function inside of the load function. I tried

 if (load.is_open())
    {
        load >> pt.x;
        load >> pt.y;
    }

but pt.x and pt.y are undefined. I'm not very good at this, but I 'm trying to understand it.

Thanks in advance!

4

5 回答 5

0

使用普通(标准)iostream对象进行序列化/反序列化可能会导致很多痛苦。

我建议您使用一些更高级别的序列化库,例如boost::archive::binary_oarchiveboost::archive::binary_iarchive链接到文档)。

它非常易于使用,避免了很多问题,并让您有机会发现一个非常有用的 C++ 库。

有关更多信息,请参阅此帖子

于 2013-06-01T07:56:24.813 回答
0

尝试这个 :

if (load.is_open())
{
while(load.good())    
{
   getline(load,point);
   pt.x=line;
   getline(load,point);
   pt.y=line;
    }
else{
 file open failed.
}

假设pt.xpt.y作为string。如果是,integer那么您需要将其转换pointinteger.

于 2013-06-01T07:58:28.930 回答
0

你不需要声明pt吗?还是它是会员?

int load ( )
    {
        POINT pt;
        ifstream load;
        load.open("coords.txt", ifstream::in);

        if (load.is_open())
        {
            load >> pt.x;
            load >> pt.y;
        }
    }
于 2013-06-01T07:58:36.393 回答
0

正如之前的海报所暗示的那样,平原iostream可能不是最好的选择......

尽管在这种情况下,您的问题似乎是POINT pt在功能范围内缺乏定义load()

也许创建一个负责设置的单例?

class MySettings
{
private:
    POINT m_pt;
public:
    static MySettings* instance()
    {
         static MySettings settings;
         return &settings;
    }

    int save(POINT pt) {...}
    POINT load() {...}
}
于 2013-06-01T08:02:46.283 回答
0

答案似乎很明显,您需要添加一个POINT参数load

/* The & symbol gives you back the points when the function has returned */
/* Alternatively, more conventionally, you may use a pointer. */

int load (POINT & pt){
    ifstream load;

    load.open("coords.txt", ifstream::in);

    if (!load.is_open()){
        cerr << "File couldn't be opened" << endl;
        return -1;
    }

    load >> pt.x;
    load >> pt.y;

    load.close();

    return 0;
}

此函数返回后,pt 参数包含您要查找的点。你可以这样称呼它:

POINT points;
load (points);
于 2013-06-01T08:14:14.163 回答