cin>>不使用getline() [英] cin>> not work with getline()
本文介绍了cin>>不使用getline()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#include <iostream>
#include <string>
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";
}
为什么当我使用uperator >>输入整数时,getline ?对于int输入,更好的用法是什么?
Why function getline() not work when I using uperator >> to input integer ? What is better use for int input ?
推荐答案
cin& > age;
,它给你一个空字符串的名称。
You still have a newline in the stream after cin>>age;
, which is giving you an empty string for the name.
你可以通过添加另一个 getline()
在获取年龄并丢弃结果后调用。另一个选项是调用 cin.ignore(BIG_NUMBER,'\\\
,其中
'); BIG_NUMBER
为MAX_INT
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.
这篇关于cin>>不使用getline()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文