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没有显示的给出的时候, 默认为' '

  • 相关阅读:
    PS总结
    有用的官方API和官网
    获取jQuery DataTables 的checked选中行
    jQuery DataTables 问题:Cannot reinitialise DataTable
    jQuery DataTables 分页
    实现页面跳转和重定向的几种方法
    iframe父页面和子页面高度自适应
    双核浏览器默认选择内核渲染自己开发的网页
    使用母版页的子页面无法显示母版页图片
    gdb安装
  • 原文地址:https://www.cnblogs.com/mr-stn/p/9527722.html
Copyright © 2011-2022 走看看