此函数可读取整行,包括前导和嵌入的空格,并将其存储在字符串对象中。
getline 函数如下所示:
getline(cin, inputLine);
其中 cin 是正在读取的输入流,而 inputLine 是接收输入字符串的 string 变量的名称。下面的程序演示了 getline 函数的应用:
// This program illustrates using the getline function //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: "; getline(cin, name); cout << "Enter the city you live in: "; getline(cin, city); cout << "Hello, " << name << endl; cout << "You live in " << city << endl; return 0; }