cin >> namel;
可以輸入 "Mark" 或 "Twain",但不能輸入 "Mark Twain",因為 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: Hello, John
You live in Doe
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; }程式輸出結果:
Please enter your name: John Doe
Enter the city you live in: Chicago
Hello, John Doe
You live in Chicago