C ++:从txt文件

时间:2017-03-14 18:16:54

标签: c++ class stream

我提前道歉,问这个问题有多糟糕,我真的在这里苦苦挣扎。 我正在编写一个名为Point in C ++的类,私有成员x和y,以及成员函数getX,getY,setX,setY,read和write。我已经能够做除读写之外的所有事情,因为我对输入/输出文件很糟糕。我有以下读写声明:

void read(istream& ins);
void write(ostream& outs);

RME如下:

* Requires: ins is in good state.
* Modifies: ins, x, y.
* Effects:  Reads point in form (x,y)

和写:

* Requires: outs is in good state.
* Modifies: outs.
* Effects:  Writes point in form (x,y).

'读'从给定的文件" data1.txt"中获取有序点,如(1,5),(2,7)等。并提取x和y成分(至少,我相信这是应该做的)。我获得了一个阅读测试套件:

void test_point() {
Point pt1;

pt1.setX(15);

cout << "pt1 is: " << pt1 << endl;

ifstream input_file;
input_file.open("data1.txt");
pt1.read(input_file);
cout << "pt1 is: " << pt1 << endl;

return;}

我真的不知道如何编写read函数。我已经尝试定义字符a,b,c和整数u,v和执行:

ins >> a >> u >> b >> v >> c;

但那并没有奏效。有人可以帮我看看如何实现这个?

1 个答案:

答案 0 :(得分:0)

你的问题中遗漏了很多东西,你需要这样才能使用这个类是可行的。首先,读取有序点的文件不应该作为成员函数实现。如果有的话,你可以使用循环:

func didBegin(_ contact: SKPhysicsContact) {

    let contactMask = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask

    switch contactMask {
    case PhysicsCategory.Circle | PhysicsCategory.square1:


        print("square 1")
    case PhysicsCategory.Circle | PhysicsCategory.square2:


        print("square 2")
    case PhysicsCategory.Circle | PhysicsCategory.square3:


        print("square 3")
    case PhysicsCategory.Circle | PhysicsCategory.square4:


        print("square 4")


   // and so on ...

    default :
        //Some other contact has occurred
        print("Some other contact")
    }


}

否则,没有合理的方法来存储您从文件中读取的一堆点。

你在read函数中对这个解决方案的想法肯定会起作用(假设字符a,b,c和ints u,v):

    while(input_file) {
        // set a point to have members x, y that were read from file
        // store this point in a vector of points
    }

事实上,使用你给我们的格式(以ifstream作为参数),在read函数中确实没有其他的东西,因为它改变了对象并且不需要返回任何东西。您的实现是在结构化文件中解析此类“记录”的最简单方法。

读完所有这些之后,将调用者对象的x坐标设置为u,将y设置为v。这应该是一个void函数,不需要返回任何内容,但应该改变它被调用的Point对象对于。应该在我提到的循环中的临时点对象上调用此成员函数,然后将该对象添加到点向量中:

    input_stream >> a >> u >> b >> v >> c;

如果实际上你需要能够读取多个点。

总之,您的阅读功能需要:

  1. 要检查ifstream是否真的很好,我还没有提及(但这是你的要求之一):

        vector<Point> points;
        while(...) {
            // declare Point
            // initialize with values from read
            points.push_back(//the point you just created);
        }
    
  2. 要读入的临时char和int变量(用作缓冲区)(顺便说一句,你甚至可以直接读入x和y而不是读入u和v然后复制,只是说)。

  3. 如果您选择不直接读入x和y,则必须将u和v值分配给x和y。现在您的对象已经完成。

  4. 对于write函数,您将使用作为参数传递给write函数的ofstream名称而不是std :: cout,并使用您显示的格式写入记录。这(实质上)与打印到控制台没有什么不同,除了输出在文本文件上。

    注意:确保您了解iostream对象(istream,ostream)和fstream(ifstream,ofstream,fstream)对象之间的区别,在这种情况下这是优选的。