詳解C++ cin.getline函數(shù)
cin
雖然可以使用 cin 和 >> 運算符來輸入字符串,但它可能會導(dǎo)致一些需要注意的問題。
當(dāng) cin 讀取數(shù)據(jù)時,它會傳遞并忽略任何前導(dǎo)白色空格字符(空格、制表符或換行符)。一旦它接觸到第一個非空格字符即開始閱讀,當(dāng)它讀取到下一個空白字符時,它將停止讀取。
例: // 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; }
預(yù)期結(jié)果:
Please enter your name: John Doe
Enter the city you live in: Chicago
Hello, John Doe
You live in Chicago
實際結(jié)果:
Please enter your name: John Doe
Enter the city you live in: Hello, John
You live in Doe
在這個示例中,用戶根本沒有機會輸入 city 城市名。因為在第一個輸入語句中,當(dāng) cin 讀取到 John 和 Doe 之間的空格時,它就會停止閱讀,只存儲 John 作為 name 的值。在第二個輸入語句中, cin 使用鍵盤緩沖區(qū)中找到的剩余字符,并存儲 Doe 作為 city 的值。
cin.getline()
cin.getline 允許讀取包含空格的字符串。它將繼續(xù)讀取,直到它讀取至最大指定的字符數(shù),或直到按下了回車鍵。
此函數(shù)會一次讀取多個字符(包括空白字符)。它以指定的地址為存放第一個讀取的字符的位置,依次向后存放讀取的字符,直到讀滿N-1個,或者遇到指定的結(jié)束符為止。若不指定結(jié)束符,則默認(rèn)結(jié)束符為'\n'。
這個函數(shù)有三個參數(shù),其語法為:cin.getline(字符指針(char*),字符個數(shù)N(int),結(jié)束符(char));
第一個參數(shù)為第一個讀取的字符的位置,通常為數(shù)組名。
第二個參數(shù)為讀取的字符的個數(shù)。
第三個參數(shù)是結(jié)束符,可以省略,省略則默認(rèn)為回車鍵結(jié)束。
例: // 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; }
輸出結(jié)果:
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.
可以看到,使用cin.getline函數(shù)輸入帶有空格的字符串。
在網(wǎng)絡(luò)編程中,寫一個簡單的回射程序時,可以使用cin.getline來輸入數(shù)據(jù)。
#define MAX_LINE 10000 char SendBuffer[MAX_LINE]; cin.getline(SendBuffer, sizeof(SendBuffer));
以上就是詳解C++ cin.getline函數(shù)的詳細(xì)內(nèi)容,更多關(guān)于cin.getline函數(shù)的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
深入解析C++中的構(gòu)造函數(shù)和析構(gòu)函數(shù)
析構(gòu)函數(shù):在撤銷對象占用的內(nèi)存之前,進行一些操作的函數(shù)。析構(gòu)函數(shù)不能被重載,只能有一個2013-09-09C語言數(shù)組越界引發(fā)的死循環(huán)問題解決
本文主要介紹了C語言數(shù)組越界引發(fā)的死循環(huán)問題解決,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08