# cin详解

C++ 专栏收录该内容
12 篇文章 0 订阅

#include <iostream>
using namespace std;
int main()
{
char str1[10], str2[10];
cin>>str1;
cin>>str2;
cout<<str1<<endl;
cout<< str2 << endl;
return 0;
}

abcd efgh

abcd
efgh

【分析】第一次读取字符串时遇到空格则停止了，将abcd读入str1，并舍弃了空格，将后面的字符串给了第二个字符串。这证明了cin读入数据遇到空格结束；并且丢弃空格符；缓冲区有残留数据，读入操作直接从缓冲区中取数据。

## cin.get(数组名，长度，结束符)

Get characters
Extracts characters from the stream, as unformatted input:

(1) single character
Extracts a single character from the stream.
The character is either returned (first signature), or set as the value of its argument (second signature).
(2) c-string
Extracts characters from the stream and stores them in s as a c-string, until either (n-1) characters have been extracted or the delimiting character is encountered: the delimiting character being either the newline character (‘\n’) or delim (if this argument is specified).
The delimiting character is not extracted from the input sequence if found, and remains there as the next character to be extracted from the stream (see getline for an alternative that does discard the delimiting character).
A null character (‘\0’) is automatically appended to the written sequence if n is greater than zero, even if an empty string is extracted.
(3) stream buffer
Extracts characters from the stream and inserts them into the output sequence controlled by the stream buffer object sb, stopping either as soon as such an insertion fails or as soon as the delimiting character is encountered in the input sequence (the delimiting character being either the newline character, ‘\n’, or delim, if this argument is specified).
Only the characters successfully inserted into sb are extracted from the stream: Neither the delimiting character, nor eventually the character that failed to be inserted at sb, are extracted from the input sequence and remain there as the next character to be extracted from the stream.

The function also stops extracting characters if the end-of-file is reached. If this is reached prematurely (before meeting the conditions described above), the function sets the eofbit flag.

Internally, the function accesses the input sequence by first constructing a sentry object (with noskipws set to true). Then (if good), it extracts characters from its associated stream buffer object as if calling its member functions sbumpc or sgetc, and finally destroys the sentry object before returning.

The number of characters successfully read and stored by this function can be accessed by calling member gcount.
Parameters
c
The reference to a character where the extracted value is stored.
s
Pointer to an array of characters where extracted characters are stored as a c-string.
If the function does not extract any characters (or if the first character extracted is the delimiter character) and n is greater than zero, this is set to an empty c-string.
n
Maximum number of characters to write to s (including the terminating null character).
If this is less than 2, the function does not extract any characters and sets failbit.
streamsize is a signed integral type.
delim
Explicit delimiting character: The operation of extracting successive characters stops as soon as the next character to extract compares equal to this.
sb
A streambuf object on whose controlled output sequence the characters are copied.
Return Value
The first signature returns the character read, or the end-of-file value (EOF) if no characters are available in the stream (note that in this case, the failbit flag is also set).

All other signatures always return *this. Note that this return value can be checked for the state of the stream (see casting a stream to bool for more info).

Errors are signaled by modifying the internal state flags:

flagerror
eofbitThe function stopped extracting characters because the input sequence has no more characters available (end-of-file reached).
failbitEither no characters were written or an empty c-string was stored in s.
badbitError on stream (such as when this function catches an exception thrown by an internal operation).When set, the integrity of the stream may have been affected.

Multiple flags may be set by a single operation.

If the operation sets an internal state flag that was registered with member exceptions, the function throws an exception of member type failure.

cin.get() 与 cin.get(char ch)用于读取字符，他们的使用是相似的，

#include <iostream>
using namespace std;
int main()
{
char c1, c2;
cin.get(c1);
cin.get(c2);
cout<<c1<<" "<<c2<<endl; // 打印两个字符
cout<<(int)c1<<" "<<(int)c2<<endl; // 打印这两个字符的ASCII值
return 0;
}

a[Enter]

a

97 10

【分析】会发现只执行了一次从键盘输入，显然第一个字符变量取的’a’, 第二个变量取的是Enter(ASCII值为10)，这是因为该函数不丢弃上次输入结束时的Enter字符，所以第一次输入结束时缓冲区中残留的是上次输入结束时的Enter字符！

a b[Enter]

a
97 32

【分析】显然第一个字符变量取的’a’, 第二个变量取的是Space(ASCII值为32)。原因同上，没有丢弃Space字符。

#include <iostream>
using namespace std;
int main ()
{
char ch, a[20];
cin.get(a, 5 , 'd');
cin>>ch;
cout<<a<<endl;
cout<<(int)ch<<endl;
return 0;
}

12345[Enter]

1234

53

【分析】第一次输入超长，字符串按长度取了”1234”，而’5′仍残留在缓冲区中，所以第二次输入字符没有从键盘读入，而是直接取了’5′，所以打印的ASCII值是53(’5′的ASCII值)。

12d45[Enter]

12

d

【分析】第二次输出为d，说明自定义结束符时不丢弃缓冲区中的结束符

## cin.getline()

Get line
Extracts characters from the stream as unformatted input and stores them into s as a c-string, until either the extracted character is the delimiting character, or n characters have been written to s (including the terminating null character).

The delimiting character is the newline character (‘\n’) for the first form, and delim for the second: when found in the input sequence, it is extracted from the input sequence, but discarded and not written to s.

The function will also stop extracting characters if the end-of-file is reached. If this is reached prematurely (before either writing n characters or finding delim), the function sets the eofbit flag.

The failbit flag is set if the function extracts no characters, or if the delimiting character is not found once (n-1) characters have already been written to s. Note that if the character that follows those (n-1) characters in the input sequence is precisely the delimiting character, it is also extracted and the failbit flag is not set (the extracted sequence was exactly n characters long).

A null character (‘\0’) is automatically appended to the written sequence if n is greater than zero, even if an empty string is extracted.

Internally, the function accesses the input sequence by first constructing a sentry object (with noskipws set to true). Then (if good), it extracts characters from its associated stream buffer object as if calling its member functions sbumpc or sgetc, and finally destroys the sentry object before returning.

The number of characters successfully read and stored by this function can be accessed by calling member gcount.

This function is overloaded for string objects in header : See getline(string).
Parameters
s
Pointer to an array of characters where extracted characters are stored as a c-string.
n
Maximum number of characters to write to s (including the terminating null character).
If the function stops reading because this limit is reached without finding the delimiting character, the failbit internal flag is set.
streamsize is a signed integral type.
delim
Explicit delimiting character: The operation of extracting successive characters stops as soon as the next character to extract compares equal to this.
Return Value
The istream object (*this).

Errors are signaled by modifying the internal state flags:

flagerror
eofbitThe function stopped extracting characters because the input sequence has no more characters available (end-of-file reached).
failbitEither the delimiting character was not found or no characters were extracted at all (because the end-of-file was before the first character or because the construction of sentry failed).
badbitError on stream (such as when this function catches an exception thrown by an internal operation).When set, the integrity of the stream may have been affected.

Multiple flags may be set by a single operation.

If the operation sets an internal state flag that was registered with member exceptions, the function throws an exception of member type failure.

cin.getline(数组名，长度，结束符) 大体与 cin.get(数组名，长度，结束符)类似。

cin.get()当输入的字符串超长时，不会引起cin函数的错误，后面的cin操作会继续执行，只是直接从缓冲区中取数据。但是cin.getline()当输入超长时，会引起cin函数的错误，后面的cin操作将不再执行。

#include <iostream>
using namespace std;
int main ()
{
char ch, a[20];
cin.getline(a, 5);
cin>>ch;
cout<<a<<endl;
cout<<(int)ch<<endl;
return 0;
}

12345[Enter]

1234
-52

【分析】与cin.get()的例子比较会发现，这里的ch并没有读取缓冲区中的5，而是返回了-52，这里其实cin>>ch语句没有执行，是因为cin出错了！

## cin.peek()

Peek next character
Returns the next character in the input sequence, without extracting it: The character is left as the next character to be extracted from the stream.

If any internal state flags is already set before the call or is set during the call, the function returns the end-of-file value (EOF).

Internally, the function accesses the input sequence by first constructing a sentry object (with noskipws set to true). Then (if good), it reads one character from its associated stream buffer object by calling its member function sgetc, and finally destroys the sentry object before returning.

Calling this function sets the value returned by gcount to zero.
Parameters
none
Return Value
The next character in the input sequence, as a value of type int.

If there are no more characters to read in the input sequence, or if any internal state flags is set, the function returns the end-of-file value (EOF), and leaves the proper internal state flags set:

flagerror
eofbitNo character could be peeked because the input sequence has no characters available (end-of-file reached).
failbitThe construction of sentry failed (such as when the stream state was not good before the call).
badbitError on stream (such as when this function catches an exception thrown by an internal operation).When set, the integrity of the stream may have been affected.

Multiple flags may be set by a single operation.

If the operation sets an internal state flag that was registered with member exceptions, the function throws an exception of member type failure.

#include <iostream>
using namespace std;
int main () {
char c;
int n;
char str[256];
cout << "Enter a number or a word: ";
c=cin.peek();
if ( (c >= '0') && (c <= '9') )
{
cin >> n;
cout << "You have entered number " << n << endl;
}
else
{
cin >> str;
cout << " You have entered word " << str << endl;
}
return 0;
}

cin.ignore()
Extracts characters from the input sequence and discards them, until either n characters have been extracted, or one compares equal to delim.

The function also stops extracting characters if the end-of-file is reached. If this is reached prematurely (before either extracting n characters or finding delim), the function sets the eofbit flag.

Internally, the function accesses the input sequence by first constructing a sentry object (with noskipws set to true). Then (if good), it extracts characters from its associated stream buffer object as if calling its member functions sbumpc or sgetc, and finally destroys the sentry object before returning.

Parameters

n
Maximum number of characters to extract (and ignore).
If this is exactly numeric_limits::max(), there is no limit: As many characters are extracted as needed until delim (or the end-of-file) is found.
streamsize is a signed integral type.
delim
Delimiting character: The function stops extracting characters as soon as an extracted character compares equal to this.
Note that the delimiting character is extracted, and thus the next input operation will continue on the character that follows it (if any).
If this is the end-of-file value (EOF), no character will compare equal, and thus exactly n characters will be discarded (unless the function fails or the end-of-file is reached).

Return Value
The istream object (*this).

Errors are signaled by modifying the internal state flags:

flagerror
eofbitThe function stopped extracting characters because the input sequence has no more characters available (end-of-file reached).
failbitThe construction of sentry failed (such as when the stream state was not good before the call).
badbitError on stream (such as when this function catches an exception thrown by an internal operation).When set, the integrity of the stream may have been affected.

Multiple flags may be set by a single operation.

If the operation sets an internal state flag that was registered with member exceptions, the function throws an exception of member type failure.

cin.ignore(a,ch)方法是从输入流（cin）中提取字符，提取的字符被忽略（ignore），不被使用。每抛弃一个字符，它都要计数和比较字符：如果计数值达到a或者被抛弃的字符是ch，则cin.ignore()函数执行终止；否则，它继续等待。它的一个常用功能就是用来清除以回车结束的输入缓冲区的内容，消除上一次输入对下一次输入的影响。比如可以这么用：cin.ignore(1024,’\n’)，通常把第一个参数设置得足够大，这样实际上总是只有第二个参数’\n’起作用，所以这一句就是把回车（包括回车）之前的所以字符从输入缓冲（流）中清除出去。

#include <iostream>
using namespace std;
void main()
{
int a,b,c;
cout<<"input a:";
cin>>a;
cin.ignore(1024, '\n');
cout<<"input b:";
cin>>b;
cin.ignore(1024, '\n');
cout<<"input c:";
cin>>c;
cout<<a<<"\t"<<b<<"\t"<<c<<endl;
}

#include<iostream>
using   namespace   std;

void main()
{
char   str1[30],str2[30],str3[30];
cout   <<   "请输入你的姓名：";
cin>>str1;
cout<<"请输入你的住址：";
cin.ignore();
cin.getline(str2,30,'a');
cout   <<   "请输入你的籍贯：";
cin.ignore();
cin.getline(str3,30);
cout<<str3;
}  

cin.putback()
Put character back
Attempts to decrease the current location in the stream by one character, making the last character extracted from the stream once again available to be extracted by input operations.

Internally, the function accesses the input sequence by first constructing a sentry object (with noskipws set to true). Then (if good), it calls sputbackc(c) on its associated stream buffer object (if any). Finally, it destroys the sentry object before returning.

If the call to sputbackc fails, the function sets the badbit flag. Note that this may happen even if c was indeed the last character extracted from the stream (depending on the internals of the associated stream buffer object).

Calling this function sets the value returned by gcount to zero.

Parameters
c
Character to be put back.
If this does not match the character at the put back position, the behavior depends on the particular stream buffer object associated to the stream:
In string buffers, the value is overwritten for output stream buffers, but the function fails on input buffers

In file buffers, the value is overwritten on the intermediate buffer (if supported): reading the character again will produce c, but the associated input sequence is not modified

Other types of stream buffer may either fail, be ignored, or overwrite the character at that position.
Return Value
The istream object (*this).

Errors are signaled by modifying the internal state flags:

flagerror
eofbit-
failbitThe construction of sentry failed (such as when the stream state was not good before the call).
badbitEither the internal call to sputbackc failed, or another error occurred on the stream (such as when the function catches an exception thrown by an internal operation, or when no stream buffer is associated with the stream).When set, the integrity of the stream may have been affected.

Multiple flags may be set by a single operation.

If the operation sets an internal state flag that was registered with member exceptions, the function throws an exception of member type failure.

putback函数调用形式为cin.putback(ch)，其作用是将前面用get或者getline函数从输入流中读取的字符ch返回到输入流，插入到当前指针的位置，供后面读取。

cin> > a;
cin> > b;

cin> > a;
cin.putback(a);
cin> > b

using namespace std;
int main () {
char c;
int n;
char str[256];
cout << "Enter a number or a word: ";
c = cin.get();
if ( (c >= '0') && (c <= '9') )
{
cin.putback (c);
cin >> n;
cout << "You have entered number " << n << endl;
}
else
{
cin.putback (c);
cin >> str;
cout << " You have entered word " << str << endl;
}
return 0;
}

cin.good()
Check whether state of stream is good
Returns true if none of the stream’s error state flags (eofbit, failbit and badbit) is set.

This function behaves as if defined as:

bool ios::good() const {
return rdstate() == goodbit;
}

Notice that this function is not the exact opposite of member bad, which only checks whether the badbit flag is set.

Whether specific error flags are set, can be checked with member functions eof, fail, and bad:

eofbit, failbit and badbit are member constants with implementation-defined values that can be combined (as if with the bitwise OR operator).
goodbit is zero, indicating that none of the other bits is set.
Parameters
none
Return Value
true if none of the stream’s state flags are set.
false if any of the stream’s state flags are set (badbit, eofbit or failbit).

cin.clear()
Set error state flags
Sets a new value for the stream’s internal error state flags.

The current value of the flags is overwritten: All bits are replaced by those in state; If state is goodbit (which is zero) all error flags are cleared.

In the case that no stream buffer is associated with the stream when this function is called, the badbit flag is automatically set (no matter the value for that bit passed in argument state).

Note that changing the state may throw an exception, depending on the latest settings passed to member exceptions.

The current state can be obtained with member function rdstate.
Parameters
state
An object of type ios_base::iostate that can take as value any combination of the following state flag member constants:

eofbit, failbit and badbit are member constants with implementation-defined values that can be combined (as if with the bitwise OR operator).
goodbit is zero, indicating that none of the other bits is set.
Return Value
none

cin.eof()
Check whether eofbit is set
Returns true if the eofbit error state flag is set for the stream.

This flag is set by all standard input operations when the End-of-File is reached in the sequence associated with the stream.

Note that the value returned by this function depends on the last operation performed on the stream (and not on the next).

Operations that attempt to read at the End-of-File fail, and thus both the eofbit and the failbit end up set. This function can be used to check whether the failure is due to reaching the End-of-File or to some other reason.

Parameters
none

Return Value
true if the stream’s eofbit error state flag is set (which signals that the End-of-File has been reached by the last input operation).
false otherwise.

cin.fail()

• 8
点赞
• 1
评论
• 34
收藏
• 打赏
• 扫一扫，分享海报

09-05 1万+

01-25 1万+
08-04 4万+
03-02 3412
05-08 1649
10-24 1474
09-25 15万+
01-15 3万+
01-06 459

¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。