1. 程式人生 > 程式設計 >詳解C++ cin.getline函式

詳解C++ cin.getline函式

cin

雖然可以使用 cin 和 >> 運算子來輸入字串,但它可能會導致一些需要注意的問題。
當 cin 讀取資料時,它會傳遞並忽略任何前導白色空格字元(空格、製表符或換行符)。一旦它接觸到第一個非空格字元即開始閱讀,當它讀取到下一個空白字元時,它將停止讀取。

例:
// This program illustrates a problem that can occur if
// cin is used to read character data into a string object.
#include <iostream>
#include <string> // Header file needed to use string objects
using namespace std;

int main()
{
  string name;
  string city;
  cout << "Please enter your name: ";
  cin >> name;
  cout << "Enter the city you live in: ";
  cin >> city;
  cout << "Hello," << name << endl;
  cout << "You live in " << city << endl;
  return 0;
}

預期結果:

Please enter your name: John Doe
Enter the city you live in: Chicago
Hello,John Doe
You live in Chicago

實際結果:

Please enter your name: John Doe
Enter the city you live in: Hello,John
You live in Doe

在這個示例中,使用者根本沒有機會輸入 city 城市名。因為在第一個輸入語句中,當 cin 讀取到 John 和 Doe 之間的空格時,它就會停止閱讀,只儲存 John 作為 name 的值。在第二個輸入語句中, cin 使用鍵盤緩衝區中找到的剩餘字元,並存儲 Doe 作為 city 的值。

cin.getline()

cin.getline 允許讀取包含空格的字串。它將繼續讀取,直到它讀取至最大指定的字元數,或直到按下了回車鍵。

此函式會一次讀取多個字元(包括空白字元)。它以指定的地址為存放第一個讀取的字元的位置,依次向後存放讀取的字元,直到讀滿N-1個,或者遇到指定的結束符為止。若不指定結束符,則預設結束符為'\n'。

這個函式有三個引數,其語法為:cin.getline(字元指標(char*),字元個數N(int),結束符(char));

第一個引數為第一個讀取的字元的位置,通常為陣列名。

第二個引數為讀取的字元的個數。

第三個引數是結束符,可以省略,省略則預設為回車鍵結束。

例:
// This program demonstrates cinT s getline function
// to read a line of text into a C-string.
#include <iostream>、
using namespace std;

int main()
{
  const int SIZE = 81;
  char sentence[SIZE];
  cout << "Enter a sentence: ";
  cin.getline (sentence,SIZE);
  cout << "You entered " << sentence << endl;
  return 0;
}

輸出結果:

Enter a sentence: To be,or not to be,that is the question.
You entered To be,that is the question.

可以看到,使用cin.getline函式輸入帶有空格的字串。

在網路程式設計中,寫一個簡單的回射程式時,可以使用cin.getline來輸入資料。

#define MAX_LINE 10000
char SendBuffer[MAX_LINE];
cin.getline(SendBuffer,sizeof(SendBuffer));

以上就是詳解C++ cin.getline函式的詳細內容,更多關於cin.getline函式的資料請關注我們其它相關文章!