c++如何文件输入到尾

#include<fstream>
#include <iostream>
#include <string>
using namespace std;

int main()
{
ifstream fin;
string a;
fin.open("StudentInformation.txt");
while(!fin.eof())
{
fin >> a;
cout << a << endl;
}
return 0;
}
为什么这样做,文件中的最后一个元素会再重复输出一遍啊?
求大侠指教啊!!!
没分了不好意思···

第1个回答  推荐于2017-09-23
将内容输出到文本中要用ofstream这个类来实现。具体步骤如下。
ofstream mycout("temp.txt");//先定义一个ofstream类对象mycout,括号里面的"temp.txt"是我们用来保存输出数据的txt文件名。这里要注意的是我们的"temp.txt"用的是相对路径,你也可以写绝对路径。
mycout<<"hello"<<endl;//这样就把"hello"输出到temp.txt文件中了
mycout.close();//最后要记得关闭打开的文件(这里打开的就是temp.txt文件)
现在给你提供一个完整的程序来实现你说的将输入的内容输出到文件

#include <iostream>
#inlcude <fstream>//ofstream类的头文件
using namespace std;

int main()
{
int n;

cin>>n;

ofstream mycout("temp.txt");

mycout<<n<<endl;

mycout.close();

return 0;

}
第2个回答  2011-11-27
eof是在文件读取结束后再读一次才会知道结束了。
所以正确的读文件的方法是:

fin>>a;
while(!fin.eof())
{
cout << a << endl;
fin >> a;
}本回答被提问者采纳
相似回答