程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> cin.get()和cin.getline()之間的差別

cin.get()和cin.getline()之間的差別

編輯:關於C++

cin.get()和cin.getline()之間的差別。本站提示廣大學習愛好者:(cin.get()和cin.getline()之間的差別)文章只能為提供參考,不一定能成為您想要的結果。以下是cin.get()和cin.getline()之間的差別正文


cin.getline()和cin.get()都是對輸出的面向行的讀取,即一次讀取整行而不是單個數字或字符,然則兩者有必定的差別。

cin.get()每次讀取一整行並把由Enter鍵生成的換行符留在輸出隊列中,好比:

#include <iostream>
using std::cin;
using std::cout;
const int SIZE = 15;
int main( ){
cout << "Enter your name:";
char name[SIZE];
cin.get(name,SIZE);
cout << "name:" << name;
cout << "\nEnter your address:";
char address[SIZE];
cin.get(address,SIZE);
cout << "address:" << address;
}

輸入:
Enter your name:jimmyi shi
name:jimmyi shi
Enter your address:address:

在這個例子中,cin.get()將輸出的名字讀取到了name中,並將由Enter生成的換行符'/n'留在了輸出隊列(即輸出緩沖區)中,是以下一次的cin.get()便在緩沖區中發明了'/n'並把它讀取了,最初形成第二次的沒法對地址的輸出並讀取。處理之道是在第一次挪用完cin.get()今後再挪用一次cin.get()把'/n'符給讀取了,可以組合式地寫為cin.get(name,SIZE).get();。

cin.getline()每次讀取一整行並把由Enter鍵生成的換行符擯棄,如:

#include <iostream>
using std::cin;
using std::cout;
const int SIZE = 15;
int main( ){
cout << "Enter your name:";
char name[SIZE];
cin.getline(name,SIZE);
cout << "name:" << name;
cout << "/nEnter your address:";
char address[SIZE];
cin.get(address,SIZE);
cout << "address:" << address;
}

輸入:
Enter your name:jimmyi shi
name:jimmyi shi
Enter your address:YN QJ
address:YN QJ

因為由Enter生成的換行符被擯棄了,所以不會影響下一次cin.get()對地址的讀取。
假如cin.get()是一個一個字符的讀入,然則cin.get()不會疏忽任何字符,關於回車符須要零丁處置。

兩點留意:
(1) 學會差別get()與getline();
(2)換行符號是\n,而不是/n;

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved