可以使用提取运算符>>
在cin
存储用户输入的字符串:
string firstName;
cout << "Type your first name: ";
cin >> firstName; // get user input from the keyboard
cout << "Your name is: " << firstName;
// Type your first name: John
// Your name is: John
然而,cin
将空格(空格、制表符等)视为终止字符,这意味着它只能存储单个单词(即使您键入许多单词):
string fullName;
cout << "Type your full name: ";
cin >> fullName;
cout << "Your name is: " << fullName;
// Type your full name: John Doe
// Your name is: John
从上面的示例中,您希望程序打印"John Doe",但它只打印"John"。
这就是为什么在使用字符串时,我们经常使用getline()
函数读取一行文本。它需要cin
作为第一个参数,字符串变量作为第二个:
string fullName;
cout << "Type your full name: ";
getline (cin, fullName);
cout << "Your name is: " << fullName;
// Type your full name: John Doe
// Your name is: John Doe
运行示例 »
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!