詳解C++ cin.getline函數(shù)
cin
雖然可以使用 cin 和 >> 運(yùn)算符來輸入字符串,但它可能會(huì)導(dǎo)致一些需要注意的問題。
當(dāng) cin 讀取數(shù)據(jù)時(shí),它會(huì)傳遞并忽略任何前導(dǎo)白色空格字符(空格、制表符或換行符)。一旦它接觸到第一個(gè)非空格字符即開始閱讀,當(dāng)它讀取到下一個(gè)空白字符時(shí),它將停止讀取。
例:
// 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
實(shí)際結(jié)果:
Please enter your name: John Doe
Enter the city you live in: Hello, John
You live in Doe
在這個(gè)示例中,用戶根本沒有機(jī)會(huì)輸入 city 城市名。因?yàn)樵诘谝粋€(gè)輸入語句中,當(dāng) cin 讀取到 John 和 Doe 之間的空格時(shí),它就會(huì)停止閱讀,只存儲(chǔ) John 作為 name 的值。在第二個(gè)輸入語句中, cin 使用鍵盤緩沖區(qū)中找到的剩余字符,并存儲(chǔ) Doe 作為 city 的值。
cin.getline()
cin.getline 允許讀取包含空格的字符串。它將繼續(xù)讀取,直到它讀取至最大指定的字符數(shù),或直到按下了回車鍵。
此函數(shù)會(huì)一次讀取多個(gè)字符(包括空白字符)。它以指定的地址為存放第一個(gè)讀取的字符的位置,依次向后存放讀取的字符,直到讀滿N-1個(gè),或者遇到指定的結(jié)束符為止。若不指定結(jié)束符,則默認(rèn)結(jié)束符為'\n'。
這個(gè)函數(shù)有三個(gè)參數(shù),其語法為:cin.getline(字符指針(char*),字符個(gè)數(shù)N(int),結(jié)束符(char));
第一個(gè)參數(shù)為第一個(gè)讀取的字符的位置,通常為數(shù)組名。
第二個(gè)參數(shù)為讀取的字符的個(gè)數(shù)。
第三個(gè)參數(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ò)編程中,寫一個(gè)簡單的回射程序時(shí),可以使用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++ 遍歷目錄下文件簡單實(shí)現(xiàn)實(shí)例
這篇文章主要介紹了c++ 遍歷文件的相關(guān)資料,這里附有實(shí)現(xiàn)實(shí)例代碼,需要的朋友可以參考下2017-02-02
詳解C++編程中用數(shù)組名作函數(shù)參數(shù)的方法
這篇文章主要介紹了詳解C++編程中用數(shù)組名作函數(shù)參數(shù)的方法,是C++入門學(xué)習(xí)中的基礎(chǔ)知識(shí),需要的朋友可以參考下2015-09-09
Qt利用QJson實(shí)現(xiàn)解析數(shù)組的示例詳解
這篇文章主要為大家詳細(xì)介紹了Qt如何利用QJson實(shí)現(xiàn)解析數(shù)組功能,文中的示例代碼講解詳細(xì),對我們學(xué)習(xí)Qt有一定幫助,需要的小伙伴可以了解一下2022-10-10

