C++ 中 Instream 的 cin 、cin.getline()、cin.get()的區別

instream 的 cin

cin使用的時候出現的問題

cin 等待用戶輸入的時候會使用空白(空格、製表符、和換行符)來確認字符串的結束位置。
如:輸入一個Alan Dreeb,那麼遇到空格了,Alan被賦值給第一個變量,Dreeb被賦值給第二個變量。

int main()
{
	char name[20];
	char favorite[20];
	cout << "enter your name:\n";
	cin >> name;
	cout >> "enter your favorite:\n";
	cin >> favorite;
	cout << "name: "<< name << endl ;
	cout << "favorite: "<< favorite;
}

	輸出結果:
	enter your name :
	Alan Yao
	enter your favorite :
	name : Alan 
	favorite: Yao

只給你輸入一個name,原因,首先Alan Yao,當cin讀取到空格,認爲已經結束了,所以在Alan後面添加\0。當程序運行到 cin >> favorite,程序讀取到Yao,所有把Yao\0賦值給favorite。

使用cin.getline()

cin.getline()是面向行輸入的,它使用的是通過回車鍵輸入的換行符來確認結尾。裏面有兩個參數,第一個是要處理的變量,第二個是要讀取的字符數(記住有一個空字符)。其中它是不保存換行符的,還有舊的庫對這個函數支持不太友好。

int main()
{
	char name[20];
	char favorite[20];
	cout << "enter your name:\n";
	cin.getline(name,20);
	cout >> "enter your favorite:\n";
	cin.getline(favorite,20);
	cout << "name: "<< name << endl ;
	cout << "favorite: "<< favorite;
}

	輸出結果:
	enter your name :
	Alan Yao
	enter your favorite :
	sport
	name : Alan Yao
	favorite: sport

使用cin.get()

爲了更加好支持舊版本的c++,還有看出用戶輸入的是什麼,檢查錯誤更加容易一些。使用cin.get()可以更加清晰。它不再讀取和丟棄換行符。參數和cin.getline()類似。

`cin.getline(name,20)==cin.get(name,20).get()`
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章