C++ 用户输入字符串


用户输入字符串

可以使用提取运算符>>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
运行示例 »