1. 程式人生 > >C++提高 10(標準輸入,輸出流,檔案io流)

C++提高 10(標準輸入,輸出流,檔案io流)

1.標準輸入流

#include<iostream>
using namespace std;

void main01()
{
	int a;
	long b;
	char c[100];

	
	cin >> a;
	cin >> b;
	//cin的這種輸入流遇到空格本次錄入結束;
	cin >> c;

	cout << "a:" << a << "b:" << b << "C:" << c << endl;
	system("pause");
}

void main02()
{
	char c;

	//這裡會先接受鍵盤錄入,放入快取區;一次取一個進行列印;
	//enter進行迴圈取出列印,取不到阻塞;ctrl+z 就是結束符EOF;結束迴圈;
	while ((c=cin.get())!=EOF)
	{
		cout << c << endl;
	}
	system("pause");
}

void main03()
{
	char a, b, c;
	//鍵盤錄入先錄入到緩衝區的;
	cin.get(a);//從緩衝區取出一個字元賦值給a,然後緩衝區中就沒有了;
	cin.get(b);
	cin.get(c);
	cout << a << b << c << endl;

	cin.putback(a);//這種是又放回到緩衝區中去;
	cin.putback(b);
	cin.putback(c);

	system("pause");
}

void main04()
{
	char a[100];
	char b[100];

	//從鍵盤錄入資料包含空格,進入緩衝區,當遇到第一個空格的之前的內容賦值給a;
	//cin.getline()會讀取緩衝區後面的內容包換空格賦值給b;
	cin >> a;
	cin.getline(b,100);
	cout << a << "---" << b << endl;
	system("pause");
}

void main()
{
	char a[100];
	char b[100];

	//從鍵盤錄入資料包含空格aa  bbccdd,進入緩衝區,當遇到第一個空格的之前的內容賦值給a;
	//cin.ignore()忽略函式;
	cin >> a;
	
	cin.ignore(2);//忽略(跳過)兩個字元;
	int a = cin.peek();//都去忽略後或者跳過後的第一個字元的阿斯克碼值;讀不到的話會阻塞在這裡;
	cin.getline(b, 100);
	cout << a << "---" << b << endl;
	system("pause");
}

2.標準輸出:

#include<iostream>
using namespace std;

void main()
{
	//cout.put('h').put('e');//put只能放一個字元進入輸出流;
	//cout << "llo" << endl;

	//char* p = "hello world";
	//cout.write(p, strlen(p)) << endl;//輸出p指標;返回一個引用
	//cout.write(p, strlen(p)-4) << endl;//輸出結果:hello w;
	//cout.write(p, strlen(p)+4) << endl;//輸出結果:hello world????;這個操作是比較危險的;可能會崩掉可能會亂碼;


	cout << "<start>";
	cout.width(30);//輸出長度為30;
	cout.fill('*');//輸出長度不夠的用*填充
	cout.setf(ios::showbase);//以16進位制輸出
	cout << hex << 1234 << "<End>" << endl;//輸出1234的16進位制
	//輸出結果:<start>*************************0x4d2<End>
	system("pause");
}



3.檔案io

#include<iostream>
#include<fstream>
using namespace std;


void main()
{
	char* fname = "C:/test.txt";
	//ios::in 可以不寫預設就是in,其他型別看下面的表格;
	ofstream fout(fname,ios::in);//建立輸出流和檔案相關;沒有檔案的話建立檔案;
	if (!fout)
	{
		cout << "檔案開啟失敗" << endl;
	}
	fout << "hello0001" << endl;
	fout << "hello0002" << endl;
	fout.close();

	ifstream fin(fname);//建立輸入流和檔案相關聯;
	char ch;
	while (fin.get(ch))
	{
		cout << ch;
	}
	fin.close();
	system("pause");
}