getline和cin混用的问题

cin/getline是什么?

  1. cin其实是一个istream对象(object),参考这里
  2. getline是一个标准库函数(function),参考这里

cin/getline停止读取的标志

  1. 用cin来读取键盘输入的时候,遇到 "空格、tab、回车" 停止读取。
  2. 用getline来读取键盘输入的时候,遇到 "回车" 停止读取。

cin/getline读取输入流的细节

  1. 当cin读取键盘输入的时候,会先判断当前读取的字符是否是 "空格,tab,回车"的一种或者几种,如果是的话,则会自动跳过,从第一个非"空格,tab,回车"字符开始读取。参考这里
    istream& operator>> (istream& is, char* s);

    Internally, the function accesses the input sequence of is by first constructing a sentry with noskipws set to false: this may flush its tied stream and/or discard leading whitespaces (see istream::sentry). 

    什么是whitespaces?从上面的网页中有相应的链接可以点出来,如下

    For the "C" locale, white-space characters are any of:

    ' '(0x20)space (SPC)
    '\t'(0x09)horizontal tab (TAB)
    '\n'(0x0a)newline (LF)
    '\v'(0x0b)vertical tab (VT)
    '\f'(0x0c)feed (FF)
    '\r'(0x0d)carriage return (CR)
  2. 当getline读取键盘输入的时候,上来就开始读取,如果遇到“回车”就停止读取,并且把读取的指针自动跳到“回车”的下一个字符(也就是说,下次getline的读取是从“回车”的下一字符开始的)。参考这里
    (1) istream& getline (istream& is, string& str, char delim);
    (2) istream& getline (istream& is, string& str);
    
    Extracts characters from is and stores them into str until the delimitation character delim is found (or the newline character, '\n', for (2)).
    If the delimiter is found, it is extracted and discarded (i.e. it is not stored and the next input operation will begin after it).
    

example

string str;
char ch;
while ( getline(cin, str) ) {
    cin >> ch;
    ...
}

如上的代码片段,当cin >> ch执行完之后,输入流中的读取指针此时执向的是 “空格、回车、tab”中的一个,假设我们输入的“回车”,当 cin >> a;执行完之后,“回车符”还保存在输入流中,然后在执行getline的时候,getline语句会立刻停止执行,因为当前指向的字符就是getline 停止读取的标志——回车符。这种执行逻辑很大可能并不是我们所需要的,此时要向让程序正确的执行,可以在cin >> ch;语句之后,加一句cin.ignore(); ingore语句默认的会让读取指针往后移动一个字符,即跳过“回车符”。参考这里

相关文章

stringstream流操作时 .clear() 与 .str("")的使用

如何使 while(getline(cin, str))或者 while(cin >> str)正常跳出循环继续剩余程序的执行

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值