Using `getline(cin, s);` after using `cin >> n;`

前端 未结 3 1384
广开言路
广开言路 2021-01-07 02:02
int n;
std::cin >> n;

std::string s = \"\";
std::getline(cin, s);

I noticed that if I use cin, my program would hang the next t

3条回答
  •  借酒劲吻你
    2021-01-07 02:18

    You need to clear the input stream - try adding the following after your cin:

    cin.clear();
    cin.ignore(std::numeric_limits::max(), '\n');
    

    The accepted answer to this question gives a good explanation of why/when this is required.

提交回复
热议问题