以下代码从用户收集信息,将输出发送到显示器,然后将相同的输出发送到文件。
#include <iostream>
#include <fstream> // for file I/O
using namespace std;
int main()
{
char automobile[50];
int year;
double a_price;
ofstream outFile; // create object for output
outFile.open("test.txt"); // associate with a file
cout << "Enter the make and model: ";
cin.getline(automobile, 50);
cout << "Enter the model year: ";
cin >> year;
cout << "Enter the price: ";
cin >> a_price;
// display information
cout << fixed;
cout.precision(2);
cout.setf(ios_base::showpoint);
cout << "Model: " << automobile << endl;
cout << "Year: " << year << endl;
cout << "$" << a_price << endl;
//File
outFile << fixed;
outFile.precision(2);
outFile.setf(ios_base::showpoint);
outFile << "Model: " << automobile << endl;
outFile << "Year: " << year << endl;
outFile << "$" << a_price << endl;
outFile.close(); // done with file
return 0;
}
上面的代码生成以下结果。
下面的程序打开用户指定的文件,从文件中读取数字,并报告值的数量,它们的总和及其平均值。
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
const int SIZE = 60;
int main()
{
char filename[SIZE];
ifstream inFile; // object for handling file input
cout << "Enter file name:";
cin.getline(filename, SIZE);
inFile.open(filename); // associate inFile with a file
if (!inFile.is_open()) // if failed to open file, error out
{
cout << "Could not open the file " << filename << endl;
cout << "Program terminating.n";
exit(EXIT_FAILURE);
}
double value;
double sum = 0.0;
int count = 0; // number of items read
inFile >> value; // get first value
while (inFile.good()) // while input good and not at EOF
{
++count; // one more item read
sum += value;
inFile >> value; // get next value
}
if (inFile.eof())
cout << "End of file reached.n";
else if (inFile.fail())
cout << "Input terminated by data mismatch.n";
else
cout << "Input terminated for unknown reason.n";
if (count == 0)
cout << "No data processed.n";
else{
cout << "Items read: " << count << endl;
cout << "Sum: " << sum << endl;
cout << "Average: " << sum / count << endl;
}
inFile.close(); // finished with the file
return 0;
}
上面的代码生成以下结果。
C++ 友元函数 C++ 类 & 对象类的友元函数是定义在类外部,但有权访问类的所有私有(private)成员和保护(protected)成员。尽管...
C++ 重载运算符和重载函数C++ 允许在同一作用域中的某个函数和运算符指定多个定义,分别称为函数重载和运算符重载。 重载声明是...
C 库函数 - vsprintf() C 标准库 - stdio.h描述C 库函数 int vsprintf(char *str, const char *format, va_list arg) 使用参数列...
C 库函数 - ctime() C 标准库 - time.h描述C 库函数 char *ctime(const time_t *timer) 返回一个表示当地时间的字符串,当地时间...
ReminderHelperjava.lang.Object |---ohos.event.notification.ReminderHelperpublic class ReminderHelperextends Object提供管...
Configurationjava.lang.Object |---ohos.global.configuration.Configurationpublic class Configurationextends Object提供资...
Closeablepublic interface Closeableextends AutoCloseableCloseable 是可以关闭的数据的源或目标。 调用 close 方法来释放对象...