更多课程 选择中心

C/C++培训
达内IT学院

400-111-8989

c语言——文件的创建与建立

  • 发布:C++培训
  • 来源:学习笔记
  • 时间:2017-08-10 13:53

今天给大家分享的是有关文件的创建与读取的语法,事实上,c语言中对于这方面的已经有相当经典且应用相当广泛的语法了,但是我今天想讲一讲关于c++中的相关语法,以下是代码:

首先是文件的创建:

# include<iostream>

# include<fstream>

# include<cstdlib>

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<iostream>

# include<fstream>

# include<iomanip>

# include<string>

# include<cstdlib>

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<fstream>包含了ofstream类,并且在主程序中使用类ofstream建立了名为outclientfile对象,并且初始化其构造函数。要注意的是我们在while只是判断条件的真假,而类outclientfile进行输入数据,在这里我也有疑问的是?在编译为什么是出现在输入数据之前的?这一点以后明白了再找机会说明,或者有知道的小伙伴也可以发消息告知我一下?

交流学习,共同进步!

预约申请免费试听课

填写下面表单即可预约申请免费试听!怕钱不够?可就业挣钱后再付学费! 怕学不会?助教全程陪读,随时解惑!担心就业?一地学习,可全国推荐就业!

上一篇:你还在为学C/C++而苦恼吗?学习方法精髓都在这
下一篇:C语言合并排序及实例代码

C语言创建windows窗口实例

C++回调函数是什么?

C++ shared_ptr和动态数组

C语言有哪些关键词,C语言44个关键词大全

  • 扫码领取资料

    回复关键字:视频资料

    免费领取 达内课程视频学习资料

  • 搜索抖音号

    搜索抖音号:1821685962

    免费领取达内课程视频学习资料

Copyright © 2021 Tedu.cn All Rights Reserved 京ICP备08000853号-56 京公网安备 11010802029508号 达内时代科技集团有限公司 版权所有

选择城市和中心
黑龙江省

吉林省

河北省

湖南省

贵州省

云南省

广西省

海南省