c++中文件输入/输出简单示例
2018-07-04 23:28
155 查看
下边的程序演示了用户输入信息,然后将信息显示到屏幕上,再将这些信息写到文件中,读者可以使用文本编辑器来查看该输出文件中的内容。
#include <iostream> #include <fstream> int main() { using namespace std; char automobile[50]; int year; double a_price; double d_price; ofstream outFile; //creat object for output outFile.open("carinfo.txt"); //associate with a file cout << "Enter the make and model of automobile: "; cin.getline(automobile,50); cout << "Enter the model year: "; cin >> year; cout << "Enter the original asking price: "; cin >> a_price; d_price = 0.913 * a_price; //display information on screen with cout 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 askiing $" << d_price << endl; //now do exact same things using outFile instead of cout outFile << fixed; outFile.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 askiing $" << d_price << endl; outFile.close(); return 0; }
在运行程序之前,文件carinfo.txt文件并不存在,在这种情况下,方法open()将新建一个名为carinfo.txt的文件。如果文件存在,默认情况下,open()将丢弃原有的内容,然后将新的输出加到给文件中。
相关文章推荐
- C++简单文件的输入/输出
- C与C++文件输入输出效率简单研究 下篇
- C++之简单文件的输入与输出
- C与C++文件输入输出效率简单研究 上篇
- c++ 简单的文件输入/输出
- 文件输入和输出简单示例
- C++中的文件输入/输出
- C++中的文件输入/输出(6):一些有用的函数
- C++中的文件输入/输出
- [置顶] C了个++:01 - C++的输入、输出和文件
- C++文件的输入和输出
- 2012/2/11 《C++ Primer Plus》第十七章:输入、输出和文件 学习笔记
- 转 C++学习笔记 之输入输出和文件
- C++中的文件输入/输出:掌握输入/…
- Qt编程11:QTextStream文件输入输出以及字符串操作的简单使用
- 有关C++输入,类,文件重定向的使用和成员函数的简单小结
- C++ 文件输入/输出(2)
- freopen - C/C++文件输入输出利器
- C++中的文件输入/输出
- 简单文件输入/输出