std :: getline on std :: cin [英] std::getline on std::cin

查看:169
本文介绍了std :: getline on std :: cin的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么好的理由为什么:

Is there any good reason why:

std::string input;
std::getline(std::cin, input);

getline调用不会等待用户输入?

the getline call won't wait for user input? Is the state of cin messed up somehow?

推荐答案

很可能你在读取一些其他数据之后读取一个字符串,

Most likely you are trying to read a string after reading some other data, say an int.

考虑输入:

11
is a prime

以下代码:

std::cin>>number;
std::getline(std::cin,input)

getline 只会在11之后读取换行符,因此你会得到它不等待用户输入的印象。

the getline will only read the newline after 11 and hence you will get the impression that it's not waiting for user input.

解决这个问题是使用一个虚拟 getline 来消费数字后的新行。

The way to resolve this is to use a dummy getline to consume the new line after the number.

这篇关于std :: getline on std :: cin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆