c语言创建与建立文件

首先是文件的创建:

include

include

include

using namespace std;

int main() {

ofstream outclientfile(“clients.dat”, ios::out);

if (!outclientfile) {

cerr << “file could not be opend” << endl;

exit(1);

}

cout << “enter the account,name,and balance.” << endl;

cout<< “enter end-of-file to end input.\n?”;

int account;

char name[30];

double balance;

while (cin >> account >> name >> balance) {

outclientfile << account << " " << name << " " << balance << endl;

cout << “?”;

}

system(“pause”);

return 0;

}

以下是文件的读取:

include

include

include

include

include

using namespace std;

void outputline(int, const string, double);

int main() {

ifstream inclientfile(“clients.dat”, ios::in);

if (!inclientfile) {

cerr << “file could not be opened” << endl;

exit(1);

}

int account;

char name[30];

double balance;

cout << left << setw(10) << “account” << setw(13) << “name”

<< “balance” << endl<<fixed<<showpoint;

while (inclientfile >> account >> name >> balance) {

outputline(account, name, balance);

}

system(“pause”);

return 0;

}

void outputline(int account, const string name, double balance) {

cout << left << setw(10) << account << setw(13) << name

<< setw(7) << setprecision(2) << right << balance << endl;

}

知识点:以文件的创建为例,我们在头文件中使用# include包含了ofstream类,并且在主程序中使用类ofstream建立了名为outclientfile对象,并且初始化其构造函数。要注意的是我们在while只是判断条件的真假,而类outclientfile进行输入数据。

发布了302 篇原创文章 · 获赞 6 · 访问量 7492
展开阅读全文
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 技术黑板 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览