C++中如何读入两个不同文档中的值呢?

来源:百度知道 编辑:UC知道 时间:2024/06/17 18:23:55
程序源代码如下:

#include<iostream>
#include<fstream>

using namespace std;

void main()
{
int a,b;
int x,y;

ifstream fin;

fin.open("D:\\1.txt");
fin>>a>>b;
cout<<"a = "<<a<<endl;
cout<<"b = "<<b<<endl;
fin.close();

fin.open("D:\\2.txt");
fin>>x>>y;
cout<<"x = "<<x<<endl;
cout<<"y = "<<y<<endl;
fin.close();
}

其中,1.txt的内容是 11 12
2.txt的内容是 21 22

但是,再读入第二个文件的时候,却老是报错,请问,该怎么修改呢???

具体什么原因不太清楚,但你可以在第二次打开文件前,先把第一次操作的信息都清空掉,即在
fin.open("D:\\2.txt");前加上
fin.clear();

据说是因为close并没有改变流的状态位什么的.

语法上没有问题。文件关闭就应当自动清除了缓冲区。
是不是别的因素造成的?

试用不同的文件流名:
ifstream fin,fin2;
...
fin2.open("D:\\2.txt");
fin2>>x>>y;
....
fin2.close();
}