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
本文链接:http://task.lmcjl.com/news/7257.html