C++标准IO库(iostream,fstream,sstream)

参考资料:

http://blog.163.com/hbu_lijian/blog/static/126129153201201710456994/

http://blog.csdn.net/stpeace/article/details/44763009



一、功能:

iosstream定义读写控制窗口的类型;

fstream定义读写已命名文件的类型;

sstream多定义的类型则用于读写存储在内存中的string对象。


二、注意:IO对象不可复制或赋值,也就无法为参数或返回值。


三、基本IO类的继承结构





四、IO标准库的条件状态:


五、字符串流
istringstream:由istream派生而来,提供读string的功能

ostringstream:由ostream派生而来,提供写string的功能

stringstream:由iostream派生而来,提供读写string的功能

string line,word;

while(getline(cin, line))

{

    istringstream string_stream(line);

    while(string_stream >> word)

        cout<


1.

ifstream infile;

infile.open(path.c_str()); 参数需转换为c类型。

if(!infile) //如果没有打开成功文件

 
  

2.

ofstream outfile;
outfile.open(path.c_str(), ofstream::app); 第二个参数默认为out,清空文件准备写。app为在文件问追加。

3.最好在打开一文件前,in.close();in.clear(); 关闭可能张打开的文件,和清空错误标志;



七、缓冲区,控制台:

1.io对象不可复制和赋值的。所以只能引用。

2.它有一些错误的标志,如strm::eofbit.可以通过s.eof()获取到01.这个以后要是有用,再细看吧。

3.cout<<"hell,I'm countryhu!"<

cout<<"hell,I'm countryhu!"<

如需刷新整个缓存则将混存数据放在unitbuf和nounitbuf之间。

4.读入前都会刷新输出。但输入与输出可以动态绑定。

cin.tie($cout);将cin与cout绑定

ostream *old_tie = cin.tie();

cin.tie(0);取消cin当前绑定


八、IOstream

#include 
using namespace std;

int main()
{
	int i = -1;
	
	cin >> i; // cin从控制台接收输入, 并保存在i中

	cout << i << endl; // count把i的值输出到控制台

	return 0;
}


九、Fstream

#include 
#include 
#include 
using namespace std;

int main()
{
	ifstream in("test.txt"); // 建立in与文件test.txt之间的额关联
	if(!in)
	{
		cout << "error" << endl;
		return 1;
	}

	string line;
	while(getline(in, line))
	{
		cout << line << endl;	
	}

	return 0;
}

十、stringstream

stringstream的对象与内存中的string对象建立关联, 往string对象写东西, 或者从string对象读取东西。

我们先看这样一个问题, 假设test.txt的内容为:

lucy 123 

lili 234 456

tom 222 456 535

jim 2345 675 34 654

其中每行第一个单词是姓名, 后面的数字都是他们的银行卡密码, 当然啦, jim的银行卡最多, 有4张, 现在, 要实现如下输出, 该怎么做呢?

lucy 123x 

lili 234x   456x 

tom 222x   456x   535x 

jim 2345x   675x   34x   654x 

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

int main()
{
	ifstream in("test.txt"); // 建立in与文件test.txt之间的额关联
	if(!in)
	{
		cout << "error" << endl;
		return 1;
	}

	string line; 
	string password;
	while(getline(in, line))
	{
		istringstream ss(line); // 建立ss与line之间的关联
		int i = 0;
		while(ss >> password) // ss从line读取东西并保存在password中
		{	
			cout << password + (1 == ++i ? "" : "x") << " ";
		}
		
		cout << endl;
	}

	return 0;
}

//利用istringstream实现字符串向数值的转化
#include 
#include 
#include 
using namespace std;

int main()
{
	int a = -1;
	string s = "101";
	istringstream is(s); // 建立关联
	cout << is.str() << endl; // 101,  看来is和s确实关联起来了啊

	is >> a;

	cout << a << endl; // 101

	return 0;
}

//把数字格式化为字符串
#include 
#include 
#include 
using namespace std;

int main()
{
	int a = -1;
	ostringstream os;
	os << "hello" << a;

	cout << os.str() << endl; // hello-1

	return 0;
}






你可能感兴趣的:(C++)