c++ - getline 和 std::istream::operator>>() 有什么区别?

标签 c++ cin istream

#include <iostream>
#include <string>

using namespace std;

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

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

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

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

最佳答案

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

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

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

关于c++ - getline 和 std::istream::operator>>() 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30005015/

相关文章:

c++ - 在 std::vector 中插入迭代器范围

c++ - 使用初始化列表初始化类成员导致内存泄漏

c++ - 不稳定的行为

c++ - 设置标准 :cin to a string

C++:提示需要多次输入数据才能继续

c++ - istream >> ostream << 使用 * 指针重载运算符

c++ - FileMapping 和 Istream Binary 之间的区别

c++ - C++ 设计中的属性处理

c++ - 使用 C++ 文件流 (fstream),如何确定文件的大小?

c++ - CvStereoCalibrate() 声明中 "InputOutputArray"的含义