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;;
    }
  • 相关阅读:
    一个关于Delphi XML处理单元的BUG
    弹出一个非阻塞对话框
    更新Delphi中SVN客户端版本的方法
    程序只允许运行一个+重复运行程序提前
    Reverse Words in a String
    How to define Servlet filter order of execution using annotations
    Understanding and Using Servlet Filters
    Observer Pattern
    javascript 比较
    SOAP vs REST
  • 原文地址:https://www.cnblogs.com/freewater/p/2892818.html
Copyright © 2011-2022 走看看