cin cin.get cin.getline getline 的区别

先看原型

cin.get() istream 流

//single character (1)
int get();
istream& get (char& c);

//c-string (2)
istream& get (char* s, streamsize n);
istream& get (char* s, streamsize n, char delim);

//stream buffer (3)
istream& get (streambuf& sb);
istream& get (streambuf& sb, char delim);

第一个函数返回读取到的 char 或者 EOF,其他函数返回 *this 也就是一个 istream&

cin.getline() istream 流

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

函数返回 *this 即 istream&

getline() string 流

//(1)
istream& getline (istream& is, string& str, char delim);
//(2)
istream& getline (istream& is, string& str);

函数返回 *this 即 istream&

cin

根据后面变量的类型读取数据。
输入结束条件:遇到Enter、Space、Tab键.
对结束符的处理 :丢弃缓冲区中使得输入结束的结束符(Enter、Space、Tab)。

如果不想跳过空格 可以通过 noskipws 流控制符来控制

cin >> noskipws >> str;

get 和 getline 的区别。

get 不会读取输入流中的 delim 字符,即 delim 字符还留在输入流中,需要手动读取并丢弃。而 getline 会读取并丢弃 delim 即输入流中不再有 delim 字符,且读取字符串中也没有 delim 字符。

cin.getcin.getline 都只能读取到 char*,而且为了安全必须指定 streamsize。

string 流中的 getline 就可以将 istream 流中的输入读取到 string 中。

因为 cin.get() 返回一个 istream 引用,所以手动丢弃 delim 时可以这么写

cin.get(ch, 10).get();

除此以外,C 中还有一些输入函数,比如 getchar scanf 等就不讨论了。

参考:

http://www.cplusplus.com/reference/iostream/istream/get/
http://www.cplusplus.com/reference/iostream/istream/getline/
http://www.cplusplus.com/reference/string/getline/