C++笔记--输入输出流

C++笔记--输入输出流,第1张

C++本身不提供输入输出 *** 作,由标准库提供;这些功能支持程序中独立于设备的输入输出 *** 作。流是程序中输入或输出设备的抽象表示,输入或输出设备是数据的来源或目的地。可以把流看作在外部设备和计算机内存之间流动的一系列字节。基本上,所有的输入和输出都是在某个外部设备上读取或写入的一系列字节。

数据传输模式
        在流中传入和传出数据有两种模式:文本模式和二进制模式。在文本模式中,数据解释为一系列字符,这些字符组织为一行或多行文本,并用换行符‘\n’断开。在文本模式中,当字符在物理设备上读写时,流可以传送换行符。流是否传送字符,以及字符如何修改都与系统有关。在二进制模式中,不允许在流中传送字符,而是传送没有经过转换的原字节。

标准流

标准流在std命名空间中定义为流类对象。这些定义在头文件iostream中:

extern istream cin;
extern ostream cout:
extern ostream cerr;
extern ostream clog;

头文件iostream也定义了对应的多字节字符流对象:

extern wistream wcin;
extern wostream wcout;
extern wostream wcerr;
extern wostream wclog;

文件流

三种流类对象可以用于处理文件:ifstream、ofstream和 fstream。这三个类的基类分别是istream、ostream和iostream。istream对象表示-一个可以读取的文件流,ofstream对象表示一个可以写入的文件输出流,fstream对象表示一一个可以读写的文件流。

看个栗子:
 

#include
#include
#include
#include 
using namespace std;


void read_file() {
	string name;
	int age;
	ifstream infile;
	infile.open("user.txt");

	while (1) {
		infile >> name;
		if (infile.eof()) {
			break;
		}
		cout << name << "\t";
		
		infile >> age;
		cout << age << endl;
	}

	infile.close();

}

void write_file() {
	/*string name;
	int age;

	ofstream outfile;

	outfile.open("user.txt", ios::out | ios::trunc);

	while (1) {
		cout << " " << endl;
		cout << "";
		cin >> name;
		if (cin.eof()) {
			break;
		}
		outfile << name << "\t";

		cout << "请输入年龄: ";
		cin >> age;
		outfile << age << endl;
	}

	outfile.close();*/
}

void write_file2() {
	const int max = 100;
	long primes[max] = {2,3,5};
	int count = 3;
	long trial = 5;
	bool isprime = true;


	do {
		trial += 2;
		int i = 0;

		do {
		
		} while (++i < count && isprime);

		if (isprime)
			*(primes + count++) - trial;

	} while (count < max);

	std::ofstream outFile("user.txt");

	for (int i = 0; i < max; i++) {
		if (i % 5 == 0)
			outFile << std::endl;
		outFile << std::setw(10) << *(primes + i);
	}
}


int main() {

	write_file2();
	return 0;
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1295366.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-10
下一篇 2022-06-10

发表评论

登录后才能评论

评论列表(0条)

保存