带空格的字符串怎么输入?

使用getline, 遇到回车完成一次输入:

#include 
#include 
using namespace std;

int main() {
    string s;

    cout << "请输入一整句话(可以包含空格):" << endl;
    getline(cin, s);  // 读取一整行,包括空格

    cout << "你输入的是:" << s << endl;

    return 0;
}

⚠️ 注意事项:

如果你在用 cin >> 读取了其他数据后,再使用 getline(),需要小心残留的换行符\n),可能会被 getline 提前读走:

int x;
cin >> x;
cin.ignore();  // 忽略掉 cin 里残留的 '\n'
getline(cin, s);

你可能感兴趣的:(LeetCode模式,转,ACM模式,c++,算法,开发语言,leetcode)