如何在使用getline()函数时从用户那里获取输入 [英] how to take input from user while using getline() function

查看:90
本文介绍了如何在使用getline()函数时从用户那里获取输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

朋友们我正面临一个问题
我已经使用cin输入了类似(cin>> ch)
的选项 那么我曾经将输入字符串作为getline(cin,string_s)
但是当我使用cin时getline无法正常工作

如果我不使用cin,效果很好
为什么会发生??
并且还有其他选择可以采用整数,然后字符串输入.通过在cin>>之后调用getline(),您实际上只是在抓取cin>>留下的换行符(和任何空白).

http://www.cplusplus.com/reference/string/getline/ [ 解决方案

getline() reads input until the newline character and cin>> fails to remove the newline character after reading input. By calling getline() after cin>>, you''re essentially just grabbing the newline character (and any white space) that cin>> left behind.

http://www.cplusplus.com/reference/string/getline/[^]

You can use getline() to get the number as well (just have to take an extra step to interpret as number).


This is what I have and it works perfectly -

using namespace std;
string str;
getline(cin, str);
cout << str << endl;


这篇关于如何在使用getline()函数时从用户那里获取输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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