知识总结顺序参考C Primer Plus(第六版)和谭浩强老师的C程序设计(第五版)等,内容以书中为标准,同时参考其它各类书籍以及优质文章,以至减少知识点上的错误,同时方便本人的基础复习,也希望能帮助到大家
最好的好人,都是犯过错误的过来人;一个人往往因为有一点小小的缺点,将来会变得更好。如有错漏之处,敬请指正,有更好的方法,也希望不吝提出。最好的生活方式就是和努力的大家,一起奔跑在路上
文章目录
- 🚀一、C++的输入和输出
- ⛳(一)C++的标准输入输出
- 🎈1.使用cout进行C++输出
- (1)格式化输出
- 🎈2.使用cin进行C++输入
- (1)cin处理单字符输入
- (2)面向行的输入:getline()和get()
- ⛳(二)文件输入/输出
- 🎈1.文件输出
- 🎈2.文件输入
- 🎈3.二进制文件的读写
- 🎈4.按指定格式读写文件
- 🎈5.文件流的状态检查与定位
🚀一、C++的输入和输出
⛳(一)C++的标准输入输出
在C语言中,我们通常会使用 scanf、printf 和其他所有标准C输入和输出函数,来对数据进行输入输出操作。在C++语言中,C语言的这一套输入输出库我们仍然能使用,但是 C++ 又增加了一套新的、更容易使用的输入输出库。即iostream库
iostream 库包含两个基础类型 istream 和 ostream,分别表示输入流和输出流。一个流就是一个字符序列,是从IO设备读出或写入IO设备的。术语“流”(stream)想要表达的是,随着时间的推移,字符是顺序生成或消耗的。
标准输入输出对象:
标准库定义了4个IO对象。为了处理输入,我们使用一个名为cin(发音为see-in)的istream类型的对象。这个对象也被称为标准输入( standard input)。对于输出,我们使用一个名为 cout(发音为 see-out)的ostream类型的对象。此对象也被称为标准输出( standard output)。标准库还定义了其他两个ostream对象,名为cerr和clog(发音分别为see-err和 see-log)。我们通常用cerr来输出警告和错误消息,因此它也被称为标准错误(standard error)。而clog用来输出程序运行时的一般性信息。
🎈1.使用cout进行C++输出
(1)基本用法:
cout ...// do stuff cin.get(ch) ; //attempt to read another char } //可改写为: while (!cin.fail()) cout.put(ch); //cout.put (char (ch)) for some implementations ++count ; ch = cin.get(); } string name; int age; ofstream outfile; //也可以使用fstream, 但是fstream的默认打开方式不截断文件长度 // ofstream的默认打开方式是, 截断式写入 ios::out | ios::trunc // fstream的默认打开方式是, 截断式写入 ios::out // 建议指定打开方式 outfile.open("user.txt", ios::out | ios::trunc); while (1) { cout //判断文件是否结束 break; } outfile string name; int age; ifstream infile; infile.open("user.txt"); while (1) { infile name; if (infile.eof()) { //判断文件是否结束 break; } cout exit(EXIT_FAILURE); } string name; int age; ofstream outfile; outfile.open("user.dat", ios::out | ios::trunc | ios::binary); while (1) { cout //判断文件是否结束 break; } outfile string name; int age; ifstream infile; infile.open("user.dat", ios::in | ios::binary); while (1) { infile name; if (infile.eof()) { //判断文件是否结束 break; } cout string name; int age; ofstream outfile; outfile.open("user.txt", ios::out | ios::trunc); while (1) { cout //判断文件是否结束 break; } cout char name[32]; int age; string line; ifstream infile; infile.open("user.txt"); while (1) { getline(infile, line); if (infile.eof()) { //判断文件是否结束 break; } sscanf_s(line.c_str(), "姓名:%s 年龄:%d", name, sizeof(name),&age); cout ifstream infile; infile.open("定位.cpp"); if (!infile.is_open()) { return 1; } infile.seekg(-50, infile.end); while (!infile.eof()) { string line; getline(infile, line); cout ifstream infile; infile.open("定位.cpp"); if (!infile.is_open()) { return 1; } // 先把文件指针移动到文件尾 infile.seekg(0, infile.end); int len = infile.tellg(); cout ofstream outfile; outfile.open("test.txt"); if (!outfile.is_open()) { return 1; } outfile