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;
}