阿稳自修室P42:文件的输入与输出

比较iostream与fstream

#include<iostream>
#include<fstream>
int main()
{
	using namespace std;

	char automobile[50];
	int year;
	double a_price;
	double d_price;

	ofstream outFile;
	outFile.open("Carinfo.txt");

	cout << "Enter the make and model of automoble:";
	cin.getline(automobile, 50);
	cout << "Enter the modle year: ";
	cin >> year;
	cout << "Enter the original asking price: ";
	cin >> a_price;
	d_price = 0.913 * a_price;

	//cout << fixed;
	//cout.precision(2);
	//cout.setf(ios_base::showpoint);
	//cout << "Make and model: " << automobile << endl;
	//cout << "year: " << year << endl;
	//cout << "was asking $" << a_price << endl;
	//cout << "Now asking $" << d_price << endl;

	outFile << fixed;
	outFile.precision(2);
	outFile.setf(ios_base::showpoint);
	outFile << "Make and model: " << automobile << endl;
	outFile << "year: " << year << endl;
	outFile << "was asking $" << a_price << endl;
	outFile << "Now asking $" << d_price << endl;

	outFile.close();
}

区别与联系

  1. #include<iostream>:iostream创建了对象即cout、cin;
  2. #include<fstream>:定义一个ofstream类的对象,由对象调用open、close;
fstream outFile; //定义一个ofstream类的对象;
outFile.open("cycandwsg.txt"); //创建一个txt文件,由对象调用,如果txt不存在即程序自己创建;若存在直接打开;
outFile << xx; //替代cout进行输出,每次弹出写入新内容时原有的txt文件内容会被覆盖;
outFile.close(); //关闭txt文件;

注意

outFile.open(“xxxx.txt”)中的文件名不区分字符大小写。

灿灿补充

outFile.open(FileName, OpenMode,FileProt)有三个参数,文件名,打开方式,文件属性,其中文件属性用的少不做讨论,补充一下打开方式的选择,如果不输入打开方式的参数则默认就是读写模式,会打开文件覆盖内容。

ios::in  为输入(读)而打开文件
ios::out  为输出(写)而打开文件
ios::ate  初始位置:文件尾
ios::app  所有输出附加在文件末尾
ios::trunc  如果文件已存在则先删除该文件
ios::binary  二进制方式
不同的方式可以一起使用,用或(|)来隔开,例如
outFile.open("xxxx.txt",ios::in|ios::out|ios::ate)

如果使用outFile.open(“xxxx.txt”,ios::app),则文件内容每次都会在最后添加而不是覆盖。

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇