zoukankan      html  css  js  c++  java
  • c++ getline的用法

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

    由getline的定义可以知道, getline返回的是一个输入流, 正常情况下输入流都是正确的, 因而

    while(getline(cin, str));

    是一个死循环无法跳出;

    Get line from stream into string

    Extracts characters from is and stores them into str until the delimitation character delim is found (or the newline character, ' ', for (2)).

    The extraction also stops if the end of file is reached in is or if some other error occurs during the input operation.

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

    Note that any content in str before the call is replaced by the newly extracted sequence.

    Each extracted character is appended to the string as if its member push_back was called.

     有定义可以知道, getline把分隔符delim之前的字符全部保存在str中, 包括空格等; 此外分隔符delim也会被吸收但是不会被保存到str中

     1 #include<iostream>
     2 #include<string>
     3 using namespace std;
     4 int main(){
     5     string str;
     6     getline(cin, str, 'A');
     7     cout<<"The string we have gotten is :"<<str<<'.'<<endl;
     8     getline(cin, str, 'B');
     9     cout<<"The string we have gotten is :"<<str<<'.'<<endl;
    10 return 0;}

    为了便于观察, 用_代替空格; 这里我们分别以'A', 'B'作为字符串输入的终止符;

    通过上面的输出可以发现'A', 'B'都不在输出字符串中, 表示这两个字符都没有被保存在输入字符串中; 

    此外, 当delim没有显示的给出的时候, 默认为' '

  • 相关阅读:
    前端面试日更解答 interview-answe 1+1 2020-04-05
    Kafka学习系列----- 消费时序图
    JVM 垃圾回收算法简析
    ORM 框架选型对比
    Spring 中的设计模式之单例模式实现
    Synchroinzed 与lock 锁的区别
    Spring源码分析之ApplicationContextAware
    Springboot 启动简析
    HTTP/2.0 简单分析
    HTTPS 原理简要分析
  • 原文地址:https://www.cnblogs.com/mr-stn/p/9527722.html
Copyright © 2011-2022 走看看