如何为我的 getline() 修复这个 cin.ignore()

How do I fix this cin.ignore() for my getline()?

本文关键字:cin ignore 我的 getline      更新时间:2023-10-16

所以我为c ++编写了一个简单的程序,我遇到了这个问题。该程序基本上要求用户输入,并且它将跳过输入后的任何空格。我试图在用户输入后使用cin.ignore(),但它不起作用。我将如何解决它?

#include<iostream>
#include<string>
using namespace std;
int main()
{
    string s;
    cout << "Your name: ";      
    getline(cin, s);
    cin.ignore();
    cout << "You entered: " << s << endl;
    return 0;
}
为什么要

使用std::cin.ignore()?假设您想跳过潜在的前导空格,您可能需要使用 std::ws

std::getline(std::cin >> std::ws, s);