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, or not to be, that is the question.
可以看到,使用cin.getline函數輸入帶有空格的字符串。
在網絡編程中,寫一個簡單的回射程序時,可以使用cin.getline來輸入數據。
#define MAX_LINE 10000 char SendBuffer[MAX_LINE]; cin.getline(SendBuffer, sizeof(SendBuffer));