您的位置:首页 > 其它

使用ofstream和ifstream

2018-03-24 04:43 225 查看
头文件iostream预先定义了一个名为cout的ostream对象, 而要使用ofstream需要用户自己声明一个对象。这个对象和cout的用法非常相似,只是cout将结果打印到屏幕上,ofstream的对象将结果写到文件里。
ofstream outFile;
outFile.open("example.txt"); //associate with a file
outFile<<fixed; //Set the floatfield format flag for the str stream to fixed.
outFile.precision(4); //set floatfield precision to 4 places
outFile<<"This is an ofstream example file!"<<endl;
outFile.close();
类似的ifstream类的对象用法和cin相似,只是需注意文件是否被成功打开,可用该对象下的is_open()方法确认。
ifstream inFile;
inFile.open("example.txt");
if(!inFile.is_open()){
exit(EXIT_FAILURE); //terminate the programm
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: