zoukankan      html  css  js  c++  java
  • getline

    getline is to read a line of characters from input stream.

    My naive implement as follows,

     1 #include<stdio.h>
     2 
     3 /* getline: get line into s, return length. 
     4 arguments: lim is the max length of s.
     5 */
     6 int getline(char s[],int lim)
     7 {
     8     int c;//store character acquired from input stream.
     9     int i=0;//index of s.
    10     while(--lim > 0 && (c=getchar())!=EOF && c!='\n')
    11     {
    12         s[i++]=c;
    13     }
    14     if(c=='\n')
    15         s[i++]=c;
    16     s[i]='\0';
    17     return i;
    18 }

    This function is very simple, but simple doesn't  indicate no bugs. When the length of characters inputed exceeds lim which is the argument of getline, getline returns wrong result. This bug can be solved by using automatic incremental string variable instead the character array.

    the Standard Template Library (STL) class in Visual C++.

    template<class _E, class _TYPE, class _A> inline 
       basic_istream<_E, _TYPE>& getline( 
       basic_istream<_E, _TYPE>& Istream, 
       basic_string<_E, _TYPE, _A>& Xstring, 
       const _E _D=_TYPE::newline( ) 
       );

    The getline function creates a string containing all of the characters from the input stream until one of the following situations occurs: - End of file. - The delimiter is encountered. - is.max_str elements have been extracted.

    Example:

    // string_getline_sample.cpp
    // compile with: /EHsc
    // Illustrates how to use the getline function to read a
    // line of text from the keyboard.
    //
    // Functions:
    //
    //    getline       Returns a string from the input stream.
    //////////////////////////////////////////////////////////////////////
    
    #pragma warning(disable:4786)
    #include <string>
    #include <iostream>
    
    using namespace std ;
    
    int main()
    {
       string s1;
       cout << "Enter a sentence (use <space> as the delimiter): ";
       getline(cin,s1, ' ');
       cout << "You entered: " << s1 << endl;;
    }
  • 相关阅读:
    Impala源码之订阅发布系统的实现
    Kylin性能调优记——业务技术两手抓
    The Beam Model:Stream &amp; Tables翻译(上)
    手把手教你搭建hadoop+hive测试环境(新手向)
    使用 Apache Atlas 进行数据治理
    类似gitlab代码提交的热力图怎么做?
    3分钟掌握一个有数小技能:回头客分析
    3分钟掌握一个有数小技能:制作动态标题
    uva 10404 Bachet's Game(完全背包)
    POJ3771+Prim
  • 原文地址:https://www.cnblogs.com/freewater/p/2892818.html
Copyright © 2011-2022 走看看