C++ 中,当使用 std::cin 进行输入时,它无法正确处理包含空格的输入。为了正确处理 C++ 中包含空格的输入,使用 std::getline 读取整行输入。该方法将捕获整个字符串,包括空格。对于 C 风格的数组,可以使用 std::cin.getline,但由于 std::string 的使用更为方便,因此通常推荐使用 std::getline。在处理前导空格时,可以使用 std::ws 来跳过空格。

1、使用 std::getline

常见的解决方案是使用 std::getline 函数,它可以读取整个输入行,包括空格。

#include <string>
#include <iostream>
using namespace std;

int main()
{
    string name, title;
    
    cout << "Enter your name: ";
    // 读取整个输入行,包括空格
    getline(cin, name);  
    
     // 读取整个输入行,包括空格
    cout << "Enter your favorite movie: ";
    getline(cin, title); 
    
    cout << name << "'s favorite movie is "
    << title << endl;
}

2、使用 std::cin.getline 处理 C 风格的输入

如正在使用 C 风格的数组(字符数组),可以使用 std::cin.getline 来读取带空格的输入。

#include <iostream>
using namespace std;

int main()
{
    char name[256], title[256];

    cout << "Enter your name: ";
    // 读取一行输入
    cin.getline(name, 256);  
    cout << "Enter your favorite movie: ";
    cin.getline(title, 256);  // 读取一行输入
    
    cout << name << "'s favorite movie is " 
    << title << endl;
}

3、使用 std::ws 跳过前导空格

在某些情况下,可能需要在调用 std::getline 之前清除输入流中的前导空格。可以使用 std::ws 操作符来跳过空格字符。

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string input;
    
    cout << "Enter a line with spaces: ";
    // 跳过前导空格后再读取一行
    getline(cin >> ws, input);  
    
    cout << "You entered: " << input << endl;
}