cin详解

输入原理
程序的输入都建有一个缓冲区,即输入缓冲区。一次输入过程是这样的,当一次键盘输入结束时会将输入的数据存入输入缓冲区,而cin函数直接从输入缓冲区中取数据。正因为cin函数是直接从缓冲区取数据的,所以有时候当缓冲区中有残留数据时,cin函数会直接取得这些残留数据而不会请求键盘输入

#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.

其中结束符为可选参数,读入的字符个数最多为(长度-1)个,结束符规定结束字符串读取的字符,默认为ENTER
若要读取字符,直接cin.get(char ch)或ch=cin.get()即可
读取字符的情况:
输入结束条件:Enter键
对结束符处理:不丢弃缓冲区中的Enter
cin.get() 与 cin.get(char ch)用于读取字符,他们的使用是相似的,
即:ch=cin.get() 与 cin.get(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字符。
读取字符串的情况:

输入结束条件:默认Enter键(因此可接受空格,Tab键),可在第三个参数上自定义结束符

对结束符处理:丢弃缓冲区中的Enter

#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.

大致意思是:
该调用形式为cin.peek() 其返回值是一个int型,其返回值是指针指向的当前字符,但它只是观测,指针仍停留在当前位置,并不后移。如果要访问的字符是文件结束符,则函数值是EOF(-1)。

#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()
Extract and discard characters
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;
}

如果没有cin.ignore(),可以一次输入3个数,用空格隔开就好了。。可是非常不美观。。这样才是我们想要的。

如果cin.ignore()不给参数,则默认参数为cin.ignore(1,EOF),即把EOF前的1个字符清掉,没有遇到EOF就清掉一个字符然后结束,会导致不正确的结果,因为EOF是文件结束标识呵。

#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;  
}  

如果在地址那里输入bcdabcd那么此时流里面剩的是bcd\n,此时cin.ignore();吃掉的就是b了,这是流里还剩下cd\n直接交给cin.getline(str3,30);应为有个\n所以这里getline就直接返回 .
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返回到输入流,插入到当前指针的位置,供后面读取。
读出来之后,再放回去,让别人也可以读 :

譬如输入了 ‘m ‘;
cin> > a;
cin> > b;
此时a= ‘m ‘,b等待你的输入
cin> > a;
cin.putback(a);
cin> > b
此时a和b都可以读回来a= ‘m’,b= ‘m’

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).

检查输入是否出错,参数无,返回值bool类型:没有出错返回true,否则返回false

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.

检查是否读到文件结尾,返回值为bool类型

cin.fail()

cin.bad()

  • 8
    点赞
  • 42
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
getline和cin都是用于从标准输入读取数据的函数,但是它们的使用方式和行为有一些别。 getline函数会将输入缓冲中的所有内容都读取完毕,包括换行符。所以如果你想在使用getline之前使用cin读取某个数据,你需要在它们之间清空输入缓冲,以免影响getline的结果。可以通过调用cin.ignore()函数来实现。 而cin会传递并忽略任何前导白色空格字符,一旦接触到第一个非空格字符即开始阅读。所以使用cin读取字符串时需要注意,如果在读取前有空格或其他空白字符,cin会将其忽略。 总结来说,getline适用于读取整行文本,包括空格和其他特殊字符,而cin适用于读取单个数据,会忽略前导空白字符。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [C++ 基础: cin和getline() 有啥别?](https://blog.csdn.net/weixin_39568531/article/details/129654332)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [详解C++ cin.getline函数](https://download.csdn.net/download/weixin_38650951/13707130)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值