为什么在写入并关闭文件后也无法读取该文件?

时间:2019-07-08 17:58:12

标签: cin cout stringstream freopen

我正在尝试

  1. 从scene.txt中读取,进行计算并写入stage1.txt

  2. 然后从stage1.txt读取并写入stage2.txt

  3. 最后,阅读stage2.txt并编写stage3.txt;

1和2正常工作。但是,我不太确定,为什么我不能做到第三呢?

我使用freopen重定向stdin和stdout,然后在从点1移到2之前,我关闭了stdin和stdout。然后再次将freopen与其他文件一起使用。

我怀疑使用stringstream会导致问题,但不能自信地说。

freopen("scene.txt","r",stdin);
freopen("stage1.txt","w",stdout);

//works fine. writes to stage1.txt

fclose(stdin);
fclose(stdout);
freopen("stage1.txt","r",stdin);
freopen("stage2.txt","w",stdout);
string test;
while(getline(cin,test))
{
    if(test=="")
    {
        cout<<endl;
        continue;
    }

    point p(1);
    stringstream s(test);

    s>>p.matrix[0]>>p.matrix[1]>>p.matrix[2];
    point res;
    res=apply_transformation(v,p);
    res.print();
}

//it also does read from stage1.txt and writes to stage2.txt


fclose(stdout);
fclose(stdin);
freopen("stage2.txt","r",stdin);
freopen("stage3.txt","w",stdout);

string test3;
while(getline(cin,test3))
{
    cout<<"YES"<<endl; //never gets here. cant even read stage2.txt
    if(test3=="")
    {
        cout<<endl;
        continue;
    }

    point p(1);
    stringstream s(test3);

    s>>p.matrix[0]>>p.matrix[1]>>p.matrix[2];
    point res;
    res=apply_transformation(P,p);
    res.print();
    cout<<p.matrix[0]<<" A "<<p.matrix[1]<<" "<<p.matrix[2]<<endl;

    //cout<<test<<endl;
}

// above-mentioned loop doesn't work. cant read from stage2 and doesn't write anything to stage3.txt

我希望以上的第3点能奏效。但事实并非如此。

1 个答案:

答案 0 :(得分:0)

我必须在3之前和2之后使用cin.clear()。问题得以解决。但是,我不知道为什么。