cin>> not work with getline()

匿名 (未验证) 提交于 2019-12-03 01:39:01

问题:

#include  #include  using namespace std;  int main () {   string str;   int age;   cout << "Please enter age: ";   cin>>age;   cout << "Please enter full name: ";   getline (cin,str);   cout << "Thank you, " << str << ".\n"; }

Why function getline() not work when I using uperator >> to input integer ? What is better use for int input ?

回答1:

You still have a newline in the stream after cin>>age;, which is giving you an empty string for the name.

You could solve it by just adding another getline() call after getting the age and throwing away the result. Another options is to call cin.ignore(BIG_NUMBER, '\n');, where BIG_NUMBER is MAX_INT or something.



回答2:

getline() won't work with an int, or any number for that matter. It is defined as such:

istream& getline (char* s, streamsize n );  istream& getline (char* s, streamsize n, char delim );

So, it takes in strings and char*'s; not digits.



转载请标明出处:cin>> not work with getline()
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!