getline和std :: istream :: operator>>>()有什么区别? [英] What's the difference between getline and std::istream::operator>>()?

查看:89
本文介绍了getline和std :: istream :: operator>>>()有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream>
#include <string>

using namespace std;

int main()
{
   string username;
   cout<< "username" ;
   cin >> username; 
}

所以我很好奇这两个代码之间的区别,我听说这是同样的事情,但是如果是的话,为什么要用两种方法呢?

So I was curious on what's the difference between these two codes, I heard it's the same thing but if it is then why two ways of doing it then?

#include <iostream>
#include <string>
using namespace std;

int main()
{  
   string username;
   cout << "username" ;
   getline (cin,username) ;
}


推荐答案

区别在于 std :: getline —顾名思义—从给定的输入流(可能是 std :: cin )和 operator>>中读取 line ; 读取一个单词 1

The difference is thatstd::getline — as the name suggests — reads a line from the given input stream (which could be, well, std::cin) and operator>> reads a word1.

即, std :: getline 读取直到找到换行符,而 operator>> 读取直到一个空格(由定义) std :: isspace )并找到。两者都从流中删除了各自的定界符,但未将其放入输出缓冲区。

That is, std::getline reads till a newline is found and operator>> reads till a space (as defined by std::isspace) and is found. Both remove their respective delimiter from the stream but don't put it in the output buffer.

1。请注意,>> 也可以读取数字— int short float char 等。

1. Note that >> can also read numbers — int, short, float, char, etc.

这篇关于getline和std :: istream :: operator&gt;&gt;&gt;()有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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