cin.getline(sentence, 20);
getline 函數使用兩個用逗號分隔的引數。第一個引數是要儲存字串的陣列的名稱。第二個引數是陣列的大小。當 cin.getline 語句執行時,cin 讀取的字元數將比該數位少一個,為 null 終止符留出空間。這樣就不需要使用 setw 操作符或 width 函數。以上語句最多可讀取 19 個字元,null 終止符將自動放在陣列最後一個字元的後面。// 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, or not to be, that is the question.