C++_Primer_chapter8 标准IO库

	
string  file = "file.txt";
ifstream ifstr;
ifstr.open(file.c_str());
if (!ifstr)
cout << "fail to open file!" << endl;
while (!ifstr.eof()) { // 在vs2015的文件夹中,我又添加了一种更简洁的方法
	string line;
	getline(ifstr, line);// 读取一行
	istringstream istringstr(line);
	/*
	string word;
	while (istringstr) {
		istringstr >> word; // 读取一个字符串
		cout << word;
	}
	*/
	//上面写法严重错误,会导致 最后一个字符被输出两次
	string word;
	while (istringstr >> word)
		cout << word;
}
ifstr.close();
int matrix[3][3] = { {0, 1, 2}, {3, 4, 5}, {6, 7, 8} };
	//ofstream::ate,打开文件定位到文件尾部; ofstream:: trunc, 清空文件流
	ofstream ofstr("file.txt", ofstream::app);	//在文件尾部添加数据
	if (!ofstr)
		cout << "fail to open file!" << endl;
	for (int i = 0; i < 3; ++i){
		ostringstream ostringstr; // 一行数据写入到string流
		for (int j = 0; j < 3; ++j) {
			ostringstr << matrix[i][j] << " ";
		}
		ofstr << ostringstr.str() << endl;// 写入到文件
	}
	ofstr.close();

template<typename T>
TreeNode<T>* buildTree(ifstream& ifstr) {
	/* 若当前字符为‘#', 生成分支结点
	 * 若为T类型,则生成叶子节点
	 * 如下方法必须掌握
	 */
	if (ifstr.eof())
		return NULL;
	TreeNode<T>* node = new TreeNode<T>();
	char ch;
	/*
	 * ifstr>>ch 自动跳过空格
	 * ifstr.peek() 不跳过空格
	*/
	ifstr >> ch;
	if (ch == symbol) {
		node->type = TreeNode<T>::TREE_INTERNAL;
		node->left = buildTree<T>(ifstr);
		node->right = buildTree<T>(ifstr);
	}
	else {
		ifstr.putback(ch); // 掌握 putback
		ifstr >> node->val;
		node->type = TreeNode<T>::TREE_LEAF;	
	}
	return node;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值